0

Hi,

I have two threads A and B. Thread A prints only odd numbers. Thread B prints only even number. I want to synchronize it in such a way that on the screen I get continues numbers. How can I do that?
I was thinking of using sockets. Thread A prints and sends a message to thread B. Thread B prints and then sends a message to thread A. Any thread before printing checks for the message from other thread and prints only if they have received the message.

Is this the best design or any of you have a better design?

Thank-you in advance,
Sri

4
Contributors
3
Replies
29
Views
4 Years
Discussion Span
Last Post by Yerbantherack
0

If you understand the synchronization it is about locking a resource which can be used by a thread at a time but does not control the behaviour of a thread completely in this case we can make use of functions which are used to wait & notify other threads. If you follow this approach hope it will help you

1

I was thinking of using sockets. Thread A prints and sends a message to thread B. Thread B prints and then sends a message to thread A. Any thread before printing checks for the message from other thread and prints only if they have received the message.

You have the right idea, but the wrong channel of communication. Communicating thread notifications through a socket is terrible from a performance point of view. All operating systems or multi-threading frameworks will provide a number of different types of thread synchronization mechanism to do this kind of thing. There are a number of approaches that could solve your problem. One solution is a condition variable which basically allows one thread to notify another of a condition. Another is a synchronization barrier which allows two threads to have a "meeting point" that both must reach before any one of them can continue. You could probably also solve your problem with a pair of mutex locks, but be wary of dead-locks. For faster operations, you can also use atomic operations on volatile flags. I think that's enough food for thoughts.

0

Thread A prints and sends a message to thread B. Thread B prints and then sends a message to thread A. Any thread before printing checks for the message from other thread and prints only if they have received the message.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.