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

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

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.