Alik Send
Alik Send

Reputation: 115

Synchronization from class Delphi

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

Upvotes: 2

Views: 972

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

I'm not 100% sure I understand, but I think you have a situation like this. You have a TThread descendent, say TMyThread. And that class in turn uses another class named TThreadClass which does not descend from TThread. You want to call Synchronize from a method of TThreadClass.

Here are some options:

  1. Pass the TThread instance to TThreadClass. This is a rather brutal solution to the problem. Now TThreadClass can do anything to the thread when all it wants to do is call Synchronize.
  2. Pass a procedural variable referring to the Synchronize method to TThreadClass. This gives TThreadClass the ability to do what it needs and no more.
  3. Call the TThread.Synchronize class method passing nil for the first parameter.

Of these, the final option is the simplest. You can do it like this:

procedure TThreadClass.SynchProc(P: TThreadProcedure);
begin
  TThread.Synchronize(nil, P);
end;

Note that it is not a good idea to pass in a TProc and cast to TThreadProcedure as 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.

Upvotes: 4

Related Questions