博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多线程一个错误的例子
阅读量:5913 次
发布时间:2019-06-19

本文共 2444 字,大约阅读时间需要 8 分钟。

见源码:

 
/*********    说明:*********    1.要让读者与写者之间、以及写者与写者之问要互斥地访同数据集;*********    2.在无写进程到来时各读者可同时访问数据集;*********    3.在读者和写者都等待时访问时写者优先.*********/#include 
#include
#include
//#include "apue.h"#define R 5 // reader NO.#define W 5 // reader and writer NO.pthread_mutex_t critical = PTHREAD_MUTEX_INITIALIZER; //保护临界资源互斥pthread_mutex_t rd = PTHREAD_MUTEX_INITIALIZER; //保护读互斥pthread_mutex_t wr = PTHREAD_MUTEX_INITIALIZER; //保护写互斥pthread_mutex_t priority = PTHREAD_MUTEX_INITIALIZER;//读写互斥int readCount = 0; //临界资源int writeCount = 0; //临界资源void* reader(void *arg){ int n = W; int id = *(int *)arg; while (1) { sleep(rand()%3); readCount++; //对于临街资源必须做到互斥访问,同一时间只有一个线程在操作. if(readCount == 1){ printf("AAAAAAAAA\n"); pthread_mutex_lock(&critical); } readCount--; sleep(rand()%3); if(readCount == 0){ printf("BBBBBBB\n"); pthread_mutex_unlock(&critical); } } printf("-----reader %d has done ----, current read count[%d]\n", id, readCount);}void *writer(void *arg){ int n = W; while(1) { sleep(rand()%3); pthread_mutex_lock(&wr); pthread_mutex_lock(&critical); //写线程之间也是互斥的. printf("\twriter is writing\n"); pthread_mutex_unlock(&critical); pthread_mutex_unlock(&wr); } printf("-----writer has done -----\n");}int main(int argc, const char *argv[]){ int err; pthread_t tid[R], writerTid; int i= 0; //for(i; i < W; ++i){
err = pthread_create(&tid[i], NULL, reader, &i); if (err != 0) { printf("can't create process for reader"); } //} err = pthread_create(&writerTid, NULL, writer, (void *)NULL); if (err != 0) { printf("can't create process for writer"); } while(1); return 0;}
 

编译运行:

AAAAAAAAA    writer is writingBBBBBBBAAAAAAAAABBBBBBB    writer is writing    writer is writing    writer is writingAAAAAAAAA    writer is writingBBBBBBB    writer is writing    writer is writingAAAAAAAAABBBBBBBAAAAAAAAA    writer is writingBBBBBBB    writer is writingAAAAAAAAABBBBBBBAAAAAAAAA    writer is writingBBBBBBB    writer is writingAAAAAAAAABBBBBBB

见上面的红色部分,之前一直以为write一定会执行在BBBB后面,因为打印完"BBBBBB"后才会释放锁.

但是这些writing 的输出其实是在"AAAAA"打印完成之后和获取锁之前执行的,write线程里面的代码和read线程代码并没有先后顺序的关系.加上锁只能让他们访问资源时互斥,并不能做到同步.

 

转载地址:http://jwmpx.baihongyu.com/

你可能感兴趣的文章
linux基础
查看>>
Factory Method模式 (一)
查看>>
java正则表达式的学习
查看>>
Linux 环境变量的配置解决(-bash: jps: command not found)问题
查看>>
redis遇到过的问题汇总(持续更新)
查看>>
组策略无法正常应用
查看>>
[转载]Monit:开源服务器监控工具
查看>>
Linux 打印 颜色显示
查看>>
dubbo请求调用过程分析
查看>>
Oracle学习(一):Oracle数据库基础
查看>>
27. Python对Mysql的操作(2)
查看>>
Linux 中用 strace 追踪系统调用和信号值
查看>>
JAVASE贪吃蛇开发记录
查看>>
mysql全文索引____ft_min_word_len
查看>>
Shiro的记住我功能失效原因
查看>>
yum方式安装mysql报错找不到mysql.sock
查看>>
PrestaShop支付接口-网银在线支付,在线支付收款,外贸收款
查看>>
JAVA 实现 基于RSA算法的签名验签
查看>>
CA ARCserve Backup系列(2)—安装代理(windows篇)
查看>>
[Unity3d for android]屏幕触摸事件
查看>>