有人可以帮我同步不同数量的线程吗?问题是当线程数可以从 1 到 9 不等时,例如当两个客户端连接到服务器时,通信应该以这种形式同步:client1、client2、client1、client2 ...直到通信结束。 我尝试使用 pthread_join、pthread_mutex_lock 和 pthread_mutex_lock,但这会阻塞 client1,直到完成通信以启动 client2。
如有任何帮助,我们将不胜感激,感谢您的回复
最佳答案
其实我不太明白线程应该如何同步。如果有一些代码块需要以序列化的方式完成,那么 pthread_mutex_lock 应该足够好。如果应该保留操作顺序 (1,2,3,1,2,3),我建议使用 pthread_mutex_lock 以及一些指示现在允许哪个线程进入临界区的变量。
// 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);
}
关于c++ - 如何同步不同数量的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1857721/