c++ - how to synchronize a varied number of threads? -
Can someone help me synchronize different numbers of threads? The problem occurs when the number of threads varies from one to nine and for example when two clients are connected to the server, the communication should be synchronized as: Client 1, Client 2, Client 1, Client 2 ... until the communication is over. I tried with pthread_join, pthread_mutex_lock and pthread_mutex_lock, but it communicates blocks to start client2 to end client1.
Any help would be appreciated and thank you for your reply
Actually do not understand how the thread should be synchronized. If some blocks of code should be done sequentially then pthread_mutex_lock should suffice. If the sequence of operations should be preserved (1,2,3,1,2,3) I recommend using pthread_mutex_lock with some variables which tells that the thread is now allowed to enter the important section .
// id_to_go ranges from 0 to number_of_thread - 1 // Each thread has my_id from the same category, while (1) {pthread_mutex_lock (mutex); If (id_to_go == my_id) {// next thread id id_to_go = (id_to_go + 1) set to% number_of_threads; } Else {// This is not our turn, please try pthread_mutex_unlock (mutex); to continue; } Handle_the_client; Pthread_mutex_unlock (mutex); }
Comments
Post a Comment