gpt4 book ai didi

c++ - 我无法按顺序排列三个线程

转载 作者:太空狗 更新时间:2023-10-29 19:53:28 26 4
gpt4 key购买 nike

我有三个要序列化的线程
我使用的 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
........
........

这是我拥有的代码。它有时会挂起,有时会运行一两个循环然后挂起。我想听听你对问题的看法。我的代码是:
线程测试.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

最佳答案

我认为问题在于 pthread_cond_signal() 可以自由选择它希望的任何等待线程,而您的代码取决于它选择特定线程。

如果我将 pthread_cond_signal() 替换为 pthread_cond_broadcast(),我将无法再让代码停止。我提到这是一个观察;我还没有说服自己这是一个正确的修复。

关于c++ - 我无法按顺序排列三个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13798342/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com