Reputation: 775
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
Upvotes: 1
Views: 245
Reputation: 466
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);
}
Upvotes: 2
Reputation: 60043
The solution is to release the lock after you've sent a message, then take it again when you want to send another one.
Upvotes: 1