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
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);
}
解决方案是在发送消息后释放锁,然后在要发送另一个消息时再次使用它。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.