簡體   English   中英

我不能得到三個線程

[英]I can not get three threads to be in order

我有三個線程,我想序列化
我使用的是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

我認為問題是pthread_cond_signal()可以自由選擇它想要的任何等待線程,而你的代碼依賴於它選擇一個特定的線程。

如果我用pthread_cond_signal()替換pthread_cond_broadcast() ,我就不能再讓代碼停止了。 我提到這是一個觀察; 我還沒有說服自己這是一個正確的解決方案。

暫且不考慮為什么要將線程序列化到這個程度的問題,問題是如果有多個線程在等待條件, 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在等待......

但是,如果你只是連續運行它們,那么有三個線程可以並行工作的用途是什么?

你應該看看這個: 死鎖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM