3个线程A,B,C分别按照顺序打印000, 111, 222.
3个线程A,B,C分别按照顺序打印0,1,2,3,4,5,6,7,8,9.
如下代码所示,但是由于线程的执行先后顺序是无序的,所以pthread_cond_signal有可能在一个线程未pthread_cond_wait之前就发出了。这种情况一般如何解决?
#include <unistd.h>#include <pthread.h>#include <ostream>#include <iostream>using namespace std ;void* routine1(void* p) ;void* routine2(void* p) ;void* routine3(void* p) ;int flag = 1 ;pthread_mutex_t mux ;//static pthread_mutexattr_t muxattr = PTHREAD_MUTEX_TIMED_NP ;static pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER ;static pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER ;static pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER ;int main(int argc, char* argv[]){ pthread_t id1, id2, id3 ; pthread_attr_t attr1, attr2, attr3 ; pthread_cond_init(&cond1, NULL) ; pthread_cond_init(&cond2, NULL) ; pthread_cond_init(&cond3, NULL) ; pthread_mutex_init(&mux, 0) ; pthread_attr_init(&attr1) ; pthread_attr_init(&attr2) ; pthread_attr_init(&attr3) ; pthread_attr_setdetachstate(&attr1, PTHREAD_CREATE_JOINABLE) ; pthread_attr_setdetachstate(&attr2, PTHREAD_CREATE_JOINABLE) ; pthread_attr_setdetachstate(&attr3, PTHREAD_CREATE_JOINABLE) ; pthread_attr_setstacksize(&attr1, 1024*100) ; pthread_attr_setstacksize(&attr2, 1024*100) ; pthread_attr_setstacksize(&attr3, 1024*100) ; pthread_create(&id1, &attr1, routine1, (void*)NULL) ; pthread_create(&id2, &attr2, routine2, (void*)NULL) ; pthread_create(&id3, &attr3, routine3, (void*)NULL) ; sleep(1) ; pthread_cond_signal(&cond1) ; pthread_join(id1, NULL) ; pthread_join(id2, NULL) ; pthread_join(id3, NULL) ; cout << "END\n" ; return 0 ;}void* routine1(void* p){ for(int i=0; i<10; i++) { pthread_mutex_lock(&mux) ; //cout<< "A lock" << endl ; pthread_cond_wait(&cond1, &mux) ; cout << "A " << i << endl ; pthread_cond_signal(&cond2) ; pthread_mutex_unlock(&mux) ; //cout << "A unlock" << endl ; } cout << "thread1 is about to exit\n" ;}void* routine2(void* p){ for(int i=0; i<10; i++) { pthread_mutex_lock(&mux) ; //cout<< "B lock" << endl ; pthread_cond_wait(&cond2, &mux) ; cout << "B " << i << endl ; pthread_cond_signal(&cond3) ; pthread_mutex_unlock(&mux) ; //cout << "B unlock" << endl ; } cout << "thread2 is about to exit\n" ;}void* routine3(void* p){ for(int i=0; i<10; i++) { pthread_mutex_lock(&mux) ; //cout<< "C lock" << endl ; pthread_cond_wait(&cond3, &mux) ; cout << "C " << i << endl ; pthread_cond_signal(&cond1) ; pthread_mutex_unlock(&mux) ; //cout << "C unlock" << endl ; } cout << "thread3 is about to exit\n" ;}semaphore s1, s2main:create thrd 1;create thrd 2;wait s1;wait s2;//working end mainthrd 1://working signal s1;end thrd 1thrd 2://working signal s2;end thrd 2