multithreading - Thread-safe in delphi -
i have modify , change visual components in thread , know it's not safe doing this.
my question how write thread-safe code? possible? if can please give me simple example?
my code not threadsafe:
type tmyworkerthread = class(tthread) public procedure execute; override; end; var form1: tform1; implementation {$r *.dfm} procedure tmyworkerthread.execute; begin //codes //working visual components end; procedure tform1.button1click(sender: tobject); begin tmyworkerthread.create(false); end;
thank you.
writing thread safe code in delphi involves basic care have in other language, means deal race conditions. race condition happens when different threads access same data. way deal declare instance of tcriticalsection , wrap dangerous code in it.
the code below shows getter , setter of property that, hypotesis, has race condition.
constructor tmythread.create; begin criticalx := tcriticalsection.create; end; destructor tmythread.destroy; override; begin freeandnil(criticalx); end; function tmythread.getx: string; begin criticalx.enter; try result := fx; criticalx.leave; end; end; procedure tmythread.setx(const value: string); begin criticalx.enter; try fx := value; criticalx.leave; end; end;
notice use of single instance of tcriticalsection (criticalx) serialize access data member fx.
however, delphi have aditional consideration! vcl not thread safe, in order avoid vcl race conditions, operation results in screen changing must run in main thread. calling such code inside synchronize method. considering class above, should this:
procedure tmythread.showx; begin synchronize(syncshowx); end; procedure tmythread.syncshowx; begin showmessage(inttostr(fx)); end;
if have delphi 2010 or later, there easier way makes use of anonymous methods:
procedure tmythread.showx; begin synchronize(procedure begin showmessage(inttostr(fx)); end); end;
i hope helps!
Comments
Post a Comment