您的位置:首页 > 运维架构 > Linux

linux环形buff模拟多线程信号量操作

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

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

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

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <semaphore.h>
#include <pthread.h>
#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多线程-互斥&条件变量与同步
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: