互斥锁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;}
关于互斥锁,同步等问题,参加上篇博客
《》