Link to home
Start Free TrialLog in
Avatar of wildzero
wildzero

asked on

TThreadList - add and deleting

Hi there,

It's that time of the year again, Thread season!
Right so I got a Boss thread, which then creates a bunch of Worker threads.

In my boss thread I have
 > FThreadList : TThreadList;
Which is created when the boss thread is created.

When the boss thread executes it creates a bunch of workers like so

      Worker := TMyWorker.Create;
      Worker.OnTerminate := OnWorkerThreadTerminate;
      myList:= FThreadList.LockList;
      try
        id := myList.Add(Worker);
        TMyWorker(myList.Items[id]).Resume;
      finally
        FThreadList.UnlockList;
      end;

Which is all good.
Now my problem is... when in my Boss.OnWorkerThreadTerminate how do I know which Worker Thread is terminating?

  myList:= FThreadList.LockList;
  try
    myList.Delete(TMyWorker(sender));
  finally
    FThreadList.UnlockList;
  end;

that gives me no love (fails to compile).

Sorry for the silly questions, lack of sleep!
Avatar of wildzero
wildzero

ASKER

This is what I have done to delete and it seems to work.

  myList:= FThreadList.LockList;
  try
    id := TMyWorker(sender).Handle;
    I  := myList.IndexOf(id);
    If i > -1 then
      begin
        myList.Delete(I);
      end;
  finally
    FThreadList.UnlockList;
  end;


That seem OK, anyone got anything better.
actually it's

  myList:= FThreadList.LockList;
  try
    id := TThread(sender).Handle;
    For i := 0 to myList.Count-1 do
      If TThread(myList.Items[i]).Handle = id then
        begin
          myList.Delete(i);
          break;
        end;
  finally
    FThreadList.UnlockList;
  end;
Avatar of TheRealLoki
procedure OnWorkerThreadTerminate(sender: TObject); <--   ;-)
wouldn't "sender" be the thread?
Sender would be the 'worker' thread, which is why when this is done
TThread(sender).Handle
it's getting the handle of the worker thread.

oh, sorry, didn't hit "submit" for a while and you added some code.
yeah, that looks ok unless you have "FreeOnTerminate := true" I think.
Although I did get an occasional error on my test app with several thousand iterations (threads just doing a random sleep) hmm...
ASKER CERTIFIED SOLUTION
Avatar of dinilud
dinilud
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
dinilud - I ended up going with that code. Just broke it out a bit so it would check that the indexof was actually > -1 (just in case). Indexof is rated faster then just doing a normal for loop aparently.