歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux環形buff模擬多線程信號量操作

Linux環形buff模擬多線程信號量操作

日期:2017/3/1 9:14:04   编辑:Linux編程

互斥鎖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多線程-互斥&條件變量與同步》http://www.linuxidc.com/Linux/2016-07/133367.htm

Copyright © Linux教程網 All Rights Reserved