Home > OS >  Linux system programming: use the semaphore semaphores and mutex mutex implement multiple producer a
Linux system programming: use the semaphore semaphores and mutex mutex implement multiple producer a

Time:11-16


As title, using mutex mutex and semaphore signal implement multiple producer and a consumer model, is originally wanted to use semaphore semaphore implementation producer consumer model, but found that can appear in multiple producers and consumers in the consumer consumption situation first, in order to achieve more producer and a consumer model must be to lock in the current thread with a mutex, but how to join sem semaphore in your code to implement multiple producers and a model of a consumer,


The code is as follows:

#include
#include
#include
Pthread_mutex_t mutex.//mutex
Pthread_cond_t empty and full;//condition variables,
Int buffer [10].//producers, consumers buffer
Void * producer (void * p) {
int i;
for(i=0; i<10; I++)
{
Pthread_mutex_lock (& amp; Mutex);//mutex, exclusive use buffer, in order to prevent multiple threads at the same time request pthread_cond_wait ()
While (buffer [I]!=0) {//used to judge the buffer
The pthread_cond_wait (& amp; The empty, & amp; Mutex);//conditions
}
Printf (" procucer produce % d \ n ", I);
Usleep (1000 * 1000/2);
Pthread_cond_signal (& amp; Full);//aroused consumer activation wait for
the condition of threadPthread_mutex_unlock (& amp; Mutex);//release the mutex
}

Pthread_exit (0);

}
Void * consumer (void * p) {
int i;
for(i=0; i<10; I++)
{
Pthread_mutex_lock (& amp; Mutex);//mutex, exclusive use buffer, in order to prevent multiple threads at the same time request pthread_cond_wait ()
While (buffer==0) {
The pthread_cond_wait (& amp; Full, & amp; Mutex);//
}
Printf (" consumer consume % d \ n ", I);
Usleep (1000 * 1000/2);
Buffer [I]=0;//removed from the buffer data
Pthread_cond_signal (& amp; The empty);//wake producers to activate wait for
the condition of threadPthread_mutex_unlock (& amp; Mutex);//release the mutex
}
Pthread_exit (0);
}
Int main () {
Pthread_t pid [3].
Pthread_mutex_init (& amp; Mutex, 0);//initialization function
Pthread_cond_init (& amp; The empty, 0);
Pthread_cond_init (& amp; Full, 0);
Pthread_create (& amp; Pid [0], NULL, producer, NULL);//create a thread
Pthread_create (& amp; Pid [1], NULL, consumer, NULL);
Pthread_create (& amp; Pid [2], NULL, producer, NULL);

for(int i=0; i<3; I++) {
Pthread_join (pid [I], 0);//wait for the end of a thread synchronization between threads operation
}
Pthread_cond_destroy (& amp; The empty);//destruction condition variables,
Pthread_cond_destroy (& amp; Full);
Pthread_mutex_destroy (& amp; Mutex);
return 0;
}
  • Related