1#include <stdio.h>
2#include <stdlib.h>
3#include <pthread.h>
4
5pthread_mutex_t Mutex;
6pthread_cond_t Cond_full;
7pthread_cond_t Cond_empty;
8
9intG_ibufsize =0;
Ten
Onevoid*thread_producer (void* Arg)
A{
- while(true)
-{
theprintf"thread_producer:pthread_mutex_lock\n");
-Pthread_mutex_lock (&mutex);
-//get lock to access, no conflict, but not necessarily meet the condition, cond is to notify the other process when the condition is met
-if(0! = g_ibufsize)//Call the wait function if the condition is not satisfied
+{
-printf"thread_producer:pthread_cond_wait cond_empty \ n");
+Pthread_cond_wait (&cond_empty, &mutex);//The premise of this sentence is that there is a lock, this time will be automatically unlocked first, until the timing of the arrival of the lock
A}
at
- //the previous wait operation already contains the yoke, which is accessed directly here
-printf"thread_producer>>>>>\n");
-G_ibufsize =1;
-
-printf"thread_producer:pthread_cond_signal\n");
inPthread_cond_signal (&cond_full);
-
toPthread_mutex_unlock (&mutex);
+}
-returnNULL;
the}
*
$void*thread_consumer (void* Arg)
Panax Notoginseng{
- while(true)
the{
+printf"thread_consumer:pthread_mutex_lock\n");
APthread_mutex_lock (&mutex);
theif(0= = g_ibufsize)
+{
-printf"thread_consumer:pthread_cond_wait\n");
$Pthread_cond_wait (&cond_full, &mutex);
$}
-
-printf"thread_consumer>>>\n");
theG_ibufsize =0;
-
Wuyiprintf"thread_consumer:pthread_cond_signal\n");
thePthread_cond_signal (&cond_empty);
-
WuPthread_mutex_unlock (&mutex);
-
About}
$returnNULL;
-}
-
-//g++-o bin1-lpthread mutithread.cpp
A
+intMain ()
the{
- void*retval1, *retval2;
$pthread_t Thread_id_1, Thread_id_2;
the
thePthread_mutex_init (&mutex, NULL);
thePthread_cond_init (&cond_full, NULL);
thePthread_cond_init (&cond_empty, NULL);
-
inPthread_cond_signal (&cond_empty);
thePthread_create (&thread_id_1, NULL, thread_producer, NULL);//int pthread_create (pthread_t *tidp, const pthread_attr_t *attr, (void*) (*START_RTN) (void*), void *arg);
thePthread_create (&thread_id_2, NULL, thread_consumer, NULL);
About
thePthread_join (Thread_id_1, &RETVAL1);//blocking and other threads are finished executing
thePthread_join (Thread_id_2, &retval2);
the
+Pthread_cond_destroy (&cond_full);
-Pthread_cond_destroy (&cond_empty);
thePthread_mutex_destroy (&mutex);
Bayi
thereturn0;
the}
Linux Ptheard producer Consumers