In Linux multithreaded synchronization, in addition to mutexes, Pthread provides another synchronization mechanism: condition variables. As with the name, the condition allows the thread to block due to some conditions that are not met.
Conditional variables are often used in conjunction with mutex amounts. This pattern is used to allow a thread to lock a variable and wait for a condition variable when it cannot get the result it expects. Finally, another thread sends a signal to him so that it can continue to execute. Pthread_cond_wait atomically invokes and unlocks the amount of mutex it holds. For this reason, the mutex is one of the parameters.
The following code demonstrates how to solve a producer consumer problem with a conditional amount.
#include <stdio.h> #include <pthread.h> #define MAX 100pthread_mutex_t the_mutex;pthread_cond_t CONDC, Condp;int buffer=0;//here for the sake of the aspect, the buffer is set to 1void *producer (void *ptr)//production data {int i;for (i=1;i<=max;i++) {Pthread_mutex_lock (&the_mutex);//Mutex using buffer while (buffer!=0) {pthread_cond_wait (&condp,&the_mutex);} Buffer=i;printf ("producer produces a product!!! \ n ");p thread_cond_signal (&CONDC);p thread_mutex_unlock (&the_mutex);} Pthread_exit (0);} void *consumer (void *ptr)//consumption data {int i;for (i=1;i<max;i++) {pthread_mutex_lock (&the_mutex);//Mutex using buffer while ( buffer==0) {pthread_cond_wait (&condc,&the_mutex);} buffer=0;printf ("Consumers consume a product!!! \ n ");p thread_cond_signal (&CONDP);p thread_mutex_unlock (&the_mutex);} Pthread_exit (0);} int main () {pthread_t pro,con;pthread_mutex_init (&the_mutex,0);p thread_cond_init (&condc,0);p Thread_cond_ Init (&condp,0);p thread_create (&con,0,consumer,0);p thread_create (&pro,0,producer,0);p Thread_join ( pro,0);p thread_join (con,0);p Thread_cond_destroy (&condc);p Thread_cond_destroy (&CONDP);p Thread_mutex_destroy (&the_mutex); return 0;}
Use the condition amount to resolve producer consumer issues