The value of the mutex mutex variable is not 0, or 1, and can only be used to represent critical resources in both states. And the semaphore is similar to that used to indicate the available resources, the difference is that the semaphore can represent multiple available resources.
-The semaphore with a value of 2 is a special mutex.
Then the simple implementation of the signal volume represents the problem of producer consumers of multiple resource accesses.
#include <stdio.h>#include<stdlib.h>#include<unistd.h>#include<semaphore.h>#include<pthread.h>#define_size_ 128intbuf[_size_];sem_t blanks;sem_t datas;//producersvoid*producter (void*val) { intBeg =0; while(1) {sem_wait (&blanks); intdata = rand ()%1024x768; Buf[beg]=data; printf ("%s done ... data =%d\n", __func__,data); Sem_post (&datas); Beg= (beg+1)%_size_; Sleep (3); } returnNULL;}//Consumervoid*consumer (void*val) { intStart =0; while(1) {sem_wait (&datas); intdata =Buf[start]; printf ("%s dene ... data =%d\n", __func__,data); Sem_post (&blanks); Start= (start+1)%_size_; Sleep (5); } returnNULL;}intMainintargcChar 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;}
About mutex, synchronization and other issues, participate in the previous blog
Linux multithreading-Mutual exclusion & conditional variables and synchronization
Linux ring buff simulates multi-threaded semaphore operation