我无法让三个线程井井有条

I can not get three threads to be in order

本文关键字:三个 线程 井井有条      更新时间:2023-10-16

我有三个线程,我想序列化
我正在使用线程是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
我认为

问题是pthread_cond_signal()可以自由选择它想要的任何等待线程,而您的代码取决于它选择特定的线程。

如果我用pthread_cond_broadcast()替换pthread_cond_signal(),我无法再让代码停止。我提到这一点是一种观察;我还没有说服自己这是一个正确的解决方案。

撇开为什么要将线程序列化到这种程度的问题不谈,问题是如果多个线程正在等待条件,pthread_cond_signal( &cond )可能只唤醒其中一个线程来检查条件(实际上这是预期和通常期望的行为 - 如果释放多个服务员,则更像是意外)。

例如,当thread_a()设置condition = 1时,它打算唤醒thread_b。 但是,thread_c可能与thread_b同时等待。 使用 pthread_cond_signal 您无法控制将释放哪些thread_bthread_c

改用pthread_cond_broadcast( &cond )唤醒所有服务员。

三个条件变量,每个线程一个。线程 A 表示一个线程 B 正在等待表单,谁向一个线程 C 等待,谁发出信号一个线程 A 正在等待......

但是,如果您只打算串行运行它们,那么拥有三个可以并行工作的线程有什么用?

你应该研究一下: 死锁