BeginThread delphi blocking function -


if using beginthread in delphi xe3 function blocked. why that?

i have tried create minimal version of problem below. 2 buttom can pressed, if presseing button btn1 caption of btn1 should change 'nooo'. if btn2 pressed btn1 caption change 'yesss'.

when btn1 pressed start thread using beginthread loops forever.

the problem then, btn1.caption := 'nooo'; never reased since beginthread blocks. shouled reach btn1.caption := 'nooo';

unit unit1;  interface  uses   winapi.windows, winapi.messages, system.sysutils, system.variants, system.classes, vcl.graphics,   vcl.controls, vcl.forms, vcl.dialogs, vcl.stdctrls;  type   tform1 = class(tform)     btn1: tbutton;     btn2: tbutton;     procedure btn1click(sender: tobject);     procedure btn2click(sender: tobject);    private     function test() : integer;     { private declarations }   public      { public declarations }   end;  var   form1: tform1;  implementation  {$r *.dfm}  function tform1.test() : integer; begin      while true     begin       sleep(random(1000) * 2);     end;     result := 0; end;  procedure tform1.btn1click(sender: tobject); var   id: longword; begin   beginthread(nil, 0, pointer(test), nil, 0, id);   btn1.caption := 'nooo'; end;  procedure tform1.btn2click(sender: tobject); begin    btn1.caption := 'yesss'; end;  end. 

the expression pointer(test) calls test() , type-casts result pointer. since test() never returns, there's no result cast, , no value pass beginthread(). beginthread() doesn't block; never gets called in first place.

the third argument beginthread() not of type pointer; of type tthreadfunc, standalone (non-member) function receives 1 pointer argument , returns integer. tform1.test() method doesn't qualify, because it's not standalone function.

make test() standalone function, , pass directly beginthread() (without type-casting or @ operator):

function test(param: pointer): integer; begin   while true     sleep(random(1000) * 2);   result := 0; end;  var   id: longword; begin   beginthread(nil, 0, test, nil, 0, id); end; 

Comments