简体   繁体   English

如何同步不同数量的线程?

[英]how to synchronize a varied number of threads?

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. 问题是,当线程数可以从1到9变化,并且例如当两个客户端连接到服务器时,通信应以以下形式进行同步:client1,client2,client1,client2 ...,直到通信结束。 I tried with pthread_join , pthread_mutex_lock and pthread_mutex_lock, but this blocks client1 until finish communicating to start client2. 我尝试使用pthread_join,pthread_mutex_lock和pthread_mutex_lock,但这会阻塞client1,直到完成通信以启动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. 如果需要以串行方式完成某些代码块,则pthread_mutex_lock应该足够好。 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. 如果应该保留操作顺序(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);
}

解决方案是在发送消息后释放锁,然后在要发送另一个消息时再次使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM