use*_*392 3 c c++ multithreading mutex pthreads
我有三个线程,我想序列化
我使用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
........
........
Run Code Online (Sandbox Code Playgroud)
这是我的代码.它有时挂起,有时会运行一个或两个循环,然后挂起.我想听听你认为的问题.我的代码是:
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);
}
Run Code Online (Sandbox Code Playgroud)
要编译代码,我使用
g++ -lpthread -std=gnu++0x thread_test.cpp
Run Code Online (Sandbox Code Playgroud)
我认为问题是pthread_cond_signal()可以随意选择它想要的等待线程,而你的代码依赖于它选择一个特定的线程.
如果我更换pthread_cond_signal()用pthread_cond_broadcast(),我不能再获取代码来搪塞.我提到这是一个观察; 我还没有说服自己这是一个正确的解决方案.