我有一个要序列化的三个线程我
使用的 pthreads 是 C++。我正在尝试对输出进行排序,使其成为 {A,B,C,A,B,C,A,B,C,................}。我这样做是因为我有太多想要序列化的线程。我想要的输出是:
Thread A
Thread B
Thread C
Thread A
Thread B
Thread C
Thread A
Thread B
Thread C
Thread A
Thread B
Thread C
........
........
这是我拥有的代码。它有时会挂起,有时会运行一两个循环然后挂起。我想听听你认为问题所在。我的代码是:
thread_test.cpp
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int condition = 0;
int count = 0;
void* thread_c( void * arg )
{
while( 1 )
{
pthread_mutex_lock( &mutex );
while( condition != 2 )
pthread_cond_wait( &cond, &mutex );
printf( "Thread C");
condition = 0;
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );
}
return( 0 );
}
void* thread_b( void * arg )
{
while( 1 )
{
pthread_mutex_lock( &mutex );
while( condition != 1 )
pthread_cond_wait( &cond, &mutex );
printf( "Thread B" );
condition = 2;
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );
}
return( 0 );
}
void* thread_a( void * arg )
{
while( 1 )
{
pthread_mutex_lock( &mutex );
while( condition != 0 )
pthread_cond_wait( &cond, &mutex );
printf( "Thread A");
condition = 1;
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );
}
return( 0 );
}
int main( void )
{
pthread_t thread_a_id;
pthread_create( &thread_a_id, NULL, &thread_a, NULL );
pthread_t thread_b_id;
pthread_create( &thread_b_id, NULL, &thread_b, NULL );
pthread_t thread_c_id;
pthread_create( &thread_c_id, NULL, &thread_c, NULL );
int a = pthread_join(thread_a_id, NULL);
int b = pthread_join(thread_b_id, NULL);
int c = pthread_join(thread_c_id, NULL);
}
为了编译代码,我使用
g++ -lpthread -std=gnu++0x thread_test.cpp