I have a question about multithreading in Delphi.
Suppose, I have a thread and I have a some class, that do some work and must have synchronization. How I can make it?
I make this procedure (In ThreadClass):
procedure TThreadClass.SynchProc(P: TProc);
begin
...
Synchronize(TThreadProcedure(P));
...
end;
And I call it from my class, that running in Thread, but …
In procedure symbol “Synchonization” is a method of TThread, that is object “(Self as TThread)”, but when I call it proc from my class, variable “Self” doesn’t contain a my ThreadClass object (I dont know, that it’s contained, may be object of second class, that running in Thread). respectively that procedure does not work.
I search oth variants (I’m passed my threadClass object to second class object and try to call “Synchronization” procedure from procedure of second class, but compiller did not want to compile it).
Can you help me? Will be grateful for any help
with greetings from Ukraine
PS Sorry for my bad English
I’m not 100% sure I understand, but I think you have a situation like this. You have a
TThreaddescendent, sayTMyThread. And that class in turn uses another class namedTThreadClasswhich does not descend fromTThread. You want to callSynchronizefrom a method ofTThreadClass.Here are some options:
TThreadinstance toTThreadClass. This is a rather brutal solution to the problem. NowTThreadClasscan do anything to the thread when all it wants to do is callSynchronize.Synchronizemethod toTThreadClass. This givesTThreadClassthe ability to do what it needs and no more.TThread.Synchronizeclass method passingnilfor the first parameter.Of these, the final option is the simplest. You can do it like this:
Note that it is not a good idea to pass in a
TProcand cast toTThreadProcedureas per the code in the question. Force the caller to pass in a procedural variable of the right type. In this case the cast is benign, but you should always aim to avoid casts.