Linux环形buff模拟多线程信号量操作Linux环形buff模拟多线程信号量操作
Linux教程
互斥锁mutex变量的值非0即1,只能用来表示两种状态下的临界资源。而信号量是与之类似的,用来表示可用资源的,区别在于,信号量可以表示多个可用资源的。
--值为2的信号量也就是特殊的互斥锁了。
那么下边就简单实现信号量表示多个资源访问的生产者消费者问题了。
#include
#include
#include
#include #include
#define _SIZE_ 128
int buf[_SIZE_];
sem_t blan...
Linux环形buff模拟多线程信号量操作
Linux教程
互斥锁mutex变量的值非0即1,只能用来
示两种状态下的临界资源。而信号量是与之类似的,用来表示可用资源的,区别在于,信号量可以表示多个可用资源的。
--值为2的信号量也就是特殊的互斥锁了。
那么下边就简单实现信号量表示多个资源访问的生产者消费者问题了。
#include
#include
#include
#include #include
#define _SIZE_ 128
int 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;
}
Linux教程
本文档为【Linux环形buff模拟多线程信号量操作】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。