views:

112

answers:

2

Hi,

Could someone please help me with synchronizing varied number of threads? The problem is when the number of threads can vary from one to 9 and when for instance two clients are connected to server, the communication should be synchronized in this form : client1, client2, client1, client2 ... until the communication is over. I tried with pthread_join , pthread_mutex_lock and pthread_mutex_lock, but this blocks client1 until finish communicating to start client2.

Any help would be appreciated and thanks for your reply

A: 

The solution is to release the lock after you've sent a message, then take it again when you want to send another one.

Anon.
+1  A: 

I actually don't understand well how the threads should be synchronized. If there is some block of code that needs to be done in a serialized manner then the pthread_mutex_lock should be good enough. If the order of operation should be preserved (1,2,3,1,2,3) I suggest using pthread_mutex_lock along with some variable indicating which thread is allowed to enter the critical section now.

// id_to_go iterates from 0 up to number_of_thread - 1
// each thread has my_id from the same range
while(1)
{
  pthread_mutex_lock(mutex);
  if (id_to_go == my_id)
  {
    // set to next thread id 
    id_to_go = (id_to_go + 1) % number_of_threads;
  }
  else
  {
    // it's not our turn, try again
    pthread_mutex_unlock(mutex);
    continue;
  }

  handle_the_client;
  pthread_mutex_unlock(mutex);
}
ja.ro
thanks for your reply. Sorry I meant varied number of threads (not invarried as it was previously )
make
And does the thread order matter to you? In such case you can replace the id_to_go with circular list of thread identifiers which inserted when new thread is created and are removed when threads are joined.In such case I would probably use separate mutexes for the thread execution block (mutex\_worker) and for the serialization of the thread list transformations (so that the new thread could be added while some other thread is serving the client)
ja.ro