Description: If you are unfamiliar with multiple threads and mutexes, please refer to the other
#include <pthread.h> #include <stdio.h> #include <stdlib.h>pthread_mutex_t mutex = pthread_mutex_ initializer;/* Initialize the mutex */pthread_cond_t cond = pthread_cond_initializer;/* Initialize the condition variable */void *thread1 (void *); void *thread2 ( void *); int i=1;int main (void) {pthread_t t_a; pthread_t T_b; Pthread_create (&t_a,null,thread1, (void *) null);/* Create Process t_a*/pthread_create (&t_b,null,thread2, (void *) NULL) ; /* Create process t_b*/pthread_join (t_a, NULL);/* Wait for process t_a to end and Windows WaitForSingleObject similar to/pthread_join (t_b, NULL);/* Wait for process T_b knot Bundles and Windows WaitForSingleObject like */* Release resources */Pthread_mutex_destroy (&MUTEX); Pthread_cond_destroy (&cond); Exit (0);} void *thread1 (void *junk) {for (i=1;i<=6;i++) {printf ("Now i =%d\n", i); Pthread_mutex_lock (&mutex);/* Lock Mutex */printf ("Thread1:lock%d\n", __line__); if (i%3==0) {printf ("Thread1:signal 1%d\n", __line__); Pthread_cond_signal (&cond);/* condition change, send signal, notify T_b process */printf ("Thread1:signal 2%d\n", __line__); sleep (1);} Pthread_mutex_unlock (&mutex);/* Unlock Mutex */printf ("Thread1:unlock%d\n\n", __line__); sleep (1);}} void *thread2 (void *junk) {while (i<6) {pthread_mutex_lock (&mutex);p rintf ("Thread2:lock%d\n", __line __), if (i%3!=0) {printf ("Thread2:wait 1%d\n", __line__); The/*pthread_cond_wait function unlocks the mutex and causes the current thread to block on the condition variable that cond points to */pthread_cond_wait (&COND,&MUTEX);/* Unlocks the mutex and waits for con D Change */printf ("Thread2:wait 2%d\n", __line__);;} Pthread_mutex_unlock (&mutex);p rintf ("Thread2:unlock%d\n\n", __line__); sleep (1);}}
[email protected]:/usr/syw/linux/thread# gcc-g threaddemo3_arg.c-o Thread3-lpthread
[Email protected]:/usr/syw/linux/thread#./thread3
Now i = 1
Thread2:lock 44
Thread2:wait 1 46
Thread1:lock 27
Thread1:unlock 35
Now i = 2
Thread1:lock 27
Thread1:unlock 35
Now i = 3
Thread1:lock 27
Thread1:signal 1 29
Thread1:signal 2 31
Thread1:unlock 35
Thread2:wait 2 49
Thread2:unlock 52
Now i = 4
Thread2:lock 44
Thread2:wait 1 46
Thread1:lock 27
Thread1:unlock 35
Now i = 5
Thread1:lock 27
Thread1:unlock 35
Now i = 6
Thread1:lock 27
Thread1:signal 1 29
Thread1:signal 2 31
Thread1:unlock 35
Thread2:wait 2 49
Thread2:unlock 52
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Linux multithreading that point