Thread context on Delphi
I am creating a server that starts a thread (listening thread). This thread listens for connections and does it's thing. Eventually it may receive some data, that I want to pass to the creator of the server:
My program --> Creates my server --> Creates the listener --> Creates a thread for every client
Now the question is: if I assign a property OnData = procedure (const Received: string) of object; to the server when I create it, and then, this same procedure is passed to the client threads, so when the thread get some data, it will be able to pass it back to the creator of the server. In pseudocode:
//My program
MyServer:= TServer.Create();
MyServer.Ondata:= SomeProcedure;
//The client thread
//When data is received
if (FServer <> ni开发者_Python百科l) then
if Assigned(FServer.Ondata) then
Fserver.Ondata(ReceivedString)..
The questions here are:
1- I understand that if 10 threads execute this procedure at the same time, the procedure will be execute in the client thread context, so is the responsibility of my program (the actual "owner" of the procedure) to synchronize. Is that right?
2- If 10 different threads execute the procedure do I have 10 "instances" of the procedure with it's own data running at the same time?
3- Do I need to protect the OnData on the Server object as well (say, with a critical section), or it's OK to leave it to the "actual" procedure?
Yes. When the thread is running, all the code it runs gets executed within its own thread context, unless that code's been sent to another thread, for example with the Synchronize method.
Almost. You have 10 instances of the TThread object, each with its own data, running at the same time. There's only one copy of the actual code to the procedure, but multiple data objects can use it at once.
Any code that's not thread-safe (that might access the VCL, or that will write to any shared data, or read from shared data that something else might write to) needs to be protected.
精彩评论