Search code examples
delphipointersbeginthread

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 other 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.


Solution

  • 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...