条件変数は、スレッド同期の別の手段であり、主なロジックは待って目を覚ますことです。条件が満たされない場合、スレッドは待ち、条件は、スレッド(、満たされている他のスレッド)ウェイク。状態変数は、一般的にので、マルチスレッドミューテックス条件を変更していることを確認する必要性、ミューテックスと組み合わせて使用されます。
関係する機能は以下のとおりです。
int型てpthread_cond_init(pthread_cond_t * 指揮、制限 のconst pthread_condattr_t * attrのを制限します)。 int型 pthread_cond_destroyは(pthread_cond_tの*の指揮); int型の pthread_cond_waitの(pthread_cond_t * 指揮を制限し、 pthread_mutex_t * mutexを制限します)。 int型 pthread_cond_signalを(pthread_cond_tの*の指揮); int型 pthread_cond_broadcastの(pthread_cond_tの*指揮);
実習:
画面上の印刷サイクル10回ABCABCは、3つのスレッドの印刷Aは、B、Cは、マルチスレッドプログラミングを使用してくださいがあります...
溶液:
する#include <stdio.hに> する#include <STDLIB.H> の#include <pthread.hの> に#define N 10 の#define M 3 // スレッドの数 pthread_mutex_tミューテックス = PTHREAD_MUTEX_INITIALIZER。 pthread_cond_t指揮; INT、M = 0 。 ボイド * thr_fn(ボイド *の引数) { int型のインデックス=(INT )引数。 チャー CH = ' ' + 指数; int型私は、 用(i = 0 ; iがN <; ++I) { pthread_mutex_lockの(&ミューテックス)。 しばらく(!インデックス= M) pthread_cond_waitの(&指揮、&ミューテックス)。 printf(" %のC " 、CH)。 M =(M + 1)%のM。 pthread_mutex_unlockの(&ミューテックス)。 pthread_cond_broadcastの(&指揮); } 戻り(ボイド *)0 。 } int型のmain() { てpthread_cond_init( &COND、NULL); がpthread_t TID [M]。 int型私は、 用(i = 0 ; iは、M <; ++ I) のpthread_create(&TID [i]は、NULL、thr_fn、(ボイド * )I); 用(i = 0 ; iは、M <; ++ I) pthread_joinを(TID [i]は、NULL); pthread_cond_destroyは(&指揮); printf(" \ nを" ); リターン 0 ; }
参照:
ます。https://www.cnblogs.com/gattaca/p/4732623.htmlで再現