linux環形buff類比多線程訊號量操作,linuxbuff
互斥鎖mutex變數的值非0即1,只能用來表示兩種狀態下的臨界資源。而訊號量是與之類似的,用來表示可用資源的,區別在於,訊號量可以表示多個可用資源的。
--值為2的訊號量也就是特殊的互斥鎖了。
那麼下邊就簡單實現訊號量表示多個資源訪問的生產者消費者問題了。
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <semaphore.h>#include <pthread.h>#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;}
關於互斥鎖,同步等問題,參加上篇部落格
《linux多線程-互斥&條件變數與同步》