Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am working on an client-server application, where each client is served on a separate thread, i met some issues when running the program, i observed that if client calls Socket.Send before server calls Socket.Receive then server blocks on Socket.Receive forever.
When running slowly in debug mode or putting a Thread.Sleep over Socket.Send everything is working normally.

My questions are:
1. Why that happens ?
2. How can i fix it ?
Posted
Updated 15-Nov-15 12:55pm
v3
Comments
Sergey Alexandrovich Kryukov 15-Nov-15 17:54pm    
"I met some issues" is not informative. But the essence of things is: if you face timing issues and rely on certain timing, your whole approach is wrong. Learn the concept of "race condition".

Now, calling "Send" before calling corresponding "Receive" is perfectly fine. If you are trying to prevent it, you are probably abusing technology.

—SA

1 solution

The question is not informative enough, so I'll just show some very basic considerations.

Calling Send before calling corresponding Receive is perfectly fine. If you are trying to prevent it, you are probably abusing technology. In terms of timing, sending and receiving operations are perfectly symmetric. Each of them can be called before data is available or is ready to be received. Each of those operations will put a calling thread in a wait state, and sitting in this state don't waste any CPU time: a thread is switched off and not scheduled for execution until it is awaken. One of the event waking up a thread is the hardware interrupt from the network, so the waiting is perfectly efficient. (Other waking up events are thread abort, interrupt, timeout, and so on.)

This is the whole basis of technology: network does the synchronization of the thread. Moreover, historically sockets have been put forward as an IPC facility (even before threads have been introduced, sockets synchronized processes and delivered data between them). Only later sockets were used for network programming.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900