This issue studies the conditional variables of pthreads. Find a study note from the Internet, see "Cnblogs-blueclue's tech Blog-posix line libraries condition variables using--pthreads line Libraries Instance Note 4".
Test the code on Windows, make a few changes, and paste the following:
There are a couple of points to note:
The delay function is sleep (), in the header file <windows.h>. The function is used to delay the execution of a thread;
The polling times are set to the condition of the while loop, and the polling times should be consistent in the signal sending and receiving functions;
#include <pthread.h> #include <stdlib.h> #include <stdio.h> #include < Windows.h>int count = 0;pthread_cond_t count_threshold_cv;pthread_mutex_t count_ Mutex;void * watch_count (void *t) { long my_id = (Long) t; while (count < 15) { pthread_mutex_lock (&count_mutex); printf ("Starting watch_count (): thread %ld\n ", my_id); printf ("Watch_count (): thread %ld going into wait ...\n", my_id); pthread_cond_wait (&count_threshold_cv, &count_mutex); /*suspend execution for an interval Of time*/ &nbsP; //sleep (100000); printf ("Watch_count ( ): thread %ld condition signal received.\n ", my_id); printf ("Watch_count (): thread %ld count now = %d.\n", my_id, count); pthread_mutex_unlock (&count_mutex ); } pthread_exit (NULL);} Void * inc_count (void *t) { long my_id = (long) t; while (count < 15) { pthread _mutex_lock (&count_mutex); count++; if (count > 10) { printf ("Inc_count (): &NBSP;THREAD&NBSP;%LD,&NBSp;count = %d threshold reached ", my_id, count); pthread_cond_signal (&COUNT_THRESHOLD_CV); printf ("just sent signal.\n"); } printf ("Inc_count (): thread %ld, count = %d, unlocking mutex\n ", my_id, count); pthread_mutex_unlock (&count_mutex); } pthread_exit (NULL);} Int main () { pthread_t threads[3]; pthread_mutex_init ( &count_mutex, null); pthread_cond_init (&count_threshold_cv, null); long t1 = 1, t2 = 2, t3 = 3;&nbSp; pthread_create (&threads[0], NULL, watch_count, (void *) t1); pthread_create (&threads[1], NULL, inc_count, (void *) t2) ; pthread_create (&threads[2], NULL, inc_count, (void *) t3 ); for (int i = 0; i < 3; i++) { pthread_join (threads[i], null); } pthread_mutex_destroy (&count_mutex); pthread_cond_destroy (&count_ THRESHOLD_CV); pthread_exit (NULL); return 0;}
This article from "Hu A Knife" blog, declined reprint!
On the conditional variables of pthread