Application example of unix mutex and semaphore
# include#include # define SIZE 3#define STR_SIZE 20pthread_mutex_t mutex; / / Global variables can be seen in sem_t read_sem for main and thread functions, and write_sem; / / global variables can be seen for main and thread functions as struct _ buf_ {char* buf [SIZE]; int front, rear;} buffer / / cyclic queue structure void thread (void) {while (1) {if (0! = sem_wait (& read_sem)) {perror ("sem_wait_0"); exit (1);} if (0! = pthread_mutex_lock (& mutex)) {perror ("pthread_mutex_lock_0"); exit (1);} fputs ("output characters:\ n", stdout); fputs (buffer.buf [buffer.front], stdout); buffer.front = (buffer.front + 1)% SIZE If (0! = pthread_mutex_unlock (& mutex)) {perror ("pthread_mutex_lock_0"); exit (1);} if (0! = sem_post (& write_sem)) {perror ("sem_wait_0"); exit (1);} sleep (10);}} int main (void) {/ / initialize the circular queue structure int iscape bufferbuffer.front = buffer.rear = 0x bufferbuffer.I