Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can not get three threads to be in order

I have a three threads that I would like to serialize
I am using pthreads is C++. I am trying to order the output so that it will be {A,B,C,A,B,C,A,B,C,...............}. I am doing this because I have so many threads that I would like to serialize. the output that I would like to have is:

Thread A
Thread B
Thread C
Thread A
Thread B
Thread C
Thread A
Thread B
Thread C
Thread A
Thread B
Thread C
........
........

This is the code that I am having. It hangs sometimes and sometime run for one or two loops and then hangs. I would like to hear what you think the problem. My code is:
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);
}

To compile the code, I use

g++ -lpthread -std=gnu++0x thread_test.cpp
like image 317
user1061392 Avatar asked Dec 20 '25 05:12

user1061392


1 Answers

I think the issue is that pthread_cond_signal() is free to pick whichever waiting thread it wishes, whereas your code depends on it picking a specific thread.

If I replace pthread_cond_signal() with pthread_cond_broadcast(), I can no longer get the code to stall. I am mentioning this as an observation; I am yet to convince myself that this is a correct fix.

like image 80
NPE Avatar answered Dec 22 '25 19:12

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!