开发者

Delphi, Passing Pointer through BeginThread

I am creating a thread using BeginThread.

In the procedure I am using to start the thread I want to pass a pointer to a boolean variable so that both the forked thread and main thread can access it as a control variable to tell one when the othe开发者_C百科r is done.

Since begin thread takes in a pointer for the parameters i have tried to pass in the Addr(MyPointerVar) but I am getting errors.

But I have to run so I cannot finish my thoughts here tonight. But if anyone has any ideas on doing this I appreciate it.


Use the '@' address operator to pass the variable's address to BeginThread(), eg:

var
  ThreadDone: Boolean;
  ThreadId: LongWord;
  ThreadHandle: Integer;

function ThreadFunc(PThreadDone: PBoolean): Integer;
begin
  ...
  PThreadDone^ := True;
  Result := 0;
end;

...

ThreadHandle := BeginThread(nil, 0, @ThreadFunc, @ThreadDone, 0, ThreadId);

With that said, another way for the main thread to check if the thread is done without using a separate variable is to pass the thread handle returned by BeginThread() to WaitForSingleObject() and see if it returns WAIT_OBJECT_0 or not:

var
  ThreadId: LongWord;
  ThreadHandle: Integer;

function ThreadFunc(Parameter: Pointer): Integer;
begin
  ...
  Result := 0;
end;

...

ThreadHandle := BeginThread(nil, 0, @ThreadFunc, nil, 0, ThreadId);
...
if WaitForSingleObject(THandle(ThreadHandle), 0) = WAIT_OBJECT_0 then
  finished...
else
  still running...


Remy's answer above is the correct solution.

I was doing what Remy has suggested above and was still having issues and with a quick test I just did it seems my fault was something dealing with having the threaded procedure in a different object than where beginthread was being called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜