Hi Gus,
I understood what you were asking. I'll explain in a bit more detail.
Unless you turn on sleep or wait mode, your CPU's keep executing instructions non-stop. And to enable multitasking, the OS gives all the processes slices of that time.
So, how does the OS keeps track of which processes get a slice of that time? When your process starts, the OS calls your function "main()". And when that returns, your process is done.
So, if you want your process to keep running, you need a loop. Most of the time a semi-endless one, that runs until it gets terminated. Around and around. But, what if you are waiting for input? What do you do?
program Example1;
var
Sock: TSocket;
function DoSomething;
var
s: string;
begin
s := Sock.Read;
//
end;
begin // this is your main(), it is called by the OS
while True do // this is your "endless" loop.
begin
if Sock.DataReady then DoSomething;
end;
end.
Of course, this turns your PC into an expensive space heater and prevents other processes to do something useful. To prevent that, you can limit the amount of time spent looking if data has been received. You can do that by adding "Sleep(xxx)", where xxx determines in how much of a hurry you are to receive that message.
But that still wastes time. The OS has to suspend another process, push its registers, switch the stack, pop yours, page the memory your process needs, if required, etc. It takes time. So, it would be even better if your process gets suspended until data is available. A blocking operation, because your process gets completely blocked from execution in the mean time. But that is exactly what you want in this case!
On a low level, the socket is a piece of hardware, that generates an interrupt when it needs attention, like when data is received. And when you tell the OS that you want to handle that event, it wakes your process when it happens.
Now is it a bit hard to generate an interrupt on a high level, so next to sleeping, you can either use a timer (but that is just a fancy way of sleeping in this case) or you can use WaitForSingleObject/WaitForMultipleObjects, that also suspend (block) your thread, until one or more other threads are done executing. In that way, you can create a thread, have it listen to the socket until something happens and terminate when it does. It sounds a bit complex (and it is often easier to have that thread process the data), but that way you can chain blocking events together.
And, if you don't want to create threads all the time, you can create mutexes instead: objects only one thread can access at any one time and that have an option to wait (block) until it is released.
Greetings, Frank