Condition variables are another means of thread synchronization, the main logic is to wait and wake up. When the condition is not satisfied, thread waits; conditions are met, thread ( other threads ) wake. Condition variables are generally used in conjunction with a mutex, because of the need to ensure that multi-threaded mutex modified conditions.
Functions involved are:
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr); int pthread_cond_destroy(pthread_cond_t *cond); int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex); int pthread_cond_signal(pthread_cond_t *cond); int pthread_cond_broadcast(pthread_cond_t *cond);
Practical Training:
There are three threads print A, B, C, please use the multi-threaded programming, printing cycle 10 times ABCABC on the screen ...
solution:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define N 10 #define M 3 //number of threads pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond; int m = 0; void* thr_fn(void *arg) { int index = (int)arg; char ch = 'A' + index; int i; for (i = 0; i < N; ++i) { pthread_mutex_lock(&mutex); while (index != m) pthread_cond_wait(&cond, &mutex); printf("%c", ch); m = (m+1) % M; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond); } return (void*)0; } int main () { pthread_cond_init(&cond, NULL); pthread_t tid[M]; int i; for (i = 0; i < M; ++i) pthread_create(&tid[i], NULL, thr_fn, (void*)i); for (i = 0; i < M; ++i) pthread_join(tid[i], NULL); pthread_cond_destroy(&cond); printf("\n"); return 0; }
REFERENCE:
[Machine] Huawei 2014 test pilot school recruit machines: multi-threaded print cycle ten times ABC
Reproduced in: https: //www.cnblogs.com/gattaca/p/4732623.html