博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux环形buff模拟多线程信号量操作
阅读量:4594 次
发布时间:2019-06-09

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

互斥锁mutex变量的值非0即1,只能用来表示两种状态下的临界资源。而信号量是与之类似的,用来表示可用资源的,区别在于,信号量可以表示多个可用资源的。

--值为2的信号量也就是特殊的互斥锁了。

那么下边就简单实现信号量表示多个资源访问的生产者消费者问题了。

#include 
#include
#include
#include
#include
#define _SIZE_ 128int buf[_SIZE_];sem_t blanks;sem_t datas;//生产者void *producter(void *val){ int beg = 0; while(1) { sem_wait(&blanks); int data = rand()%1024; buf[beg] = data; printf("%s done... data = %d\n",__func__,data); sem_post(&datas); beg = (beg+1)%_SIZE_; sleep(3); } return NULL;}//消费者void *consumer(void *val){ int start = 0; while(1) { sem_wait(&datas); int data = buf[start]; printf("%s dene... data = %d\n", __func__,data); sem_post(&blanks); start = (start+1)%_SIZE_; sleep(5); } return NULL;}int main(int argc, char const *argv[]){ sem_init(&blanks,0,_SIZE_); sem_init(&datas,0,0); pthread_t id1,id2; pthread_create(&id1,NULL,producter,NULL); pthread_create(&id2,NULL,consumer,NULL); pthread_join(id1,NULL); pthread_join(id2,NULL); sem_destroy(&blanks); sem_destroy(&datas); return 0;}

关于互斥锁,同步等问题,参加上篇博客

《》

 

转载于:https://www.cnblogs.com/lang5230/p/5686869.html

你可能感兴趣的文章
赋值文件
查看>>
Vue 数组 字典 template v-for 的使用
查看>>
蓝牙模块选择经验谈
查看>>
java中==和equals
查看>>
CCActionPageTurn3D
查看>>
python random
查看>>
esp32-智能语音-cli(调试交互命令)
查看>>
netty与MQ使用心得
查看>>
关于dl dt dd 文字过长换行在移动端显示对齐的探讨总结
查看>>
swoolefy PHP的异步、并行、高性能网络通信引擎内置了Http/WebSocket服务器端/客户端...
查看>>
Python学习笔记
查看>>
unshift()与shift()
查看>>
使用 NPOI 、aspose实现execl模板公式计算
查看>>
行为型模式:中介者模式
查看>>
How to Notify Command to evaluate in mvvmlight
查看>>
33. Search in Rotated Sorted Array
查看>>
461. Hamming Distance
查看>>
Python垃圾回收机制详解
查看>>
{面试题1: 赋值运算符函数}
查看>>
Node中没搞明白require和import,你会被坑的很惨
查看>>