We help IT Professionals succeed at work.

TThreadList - add and deleting

wildzero
wildzero asked
on
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!
Comment
Watch Question

Author

Commented:
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.

Author

Commented:
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;
TheRealLokiSenior Developer
CERTIFIED EXPERT

Commented:
procedure OnWorkerThreadTerminate(sender: TObject); <--   ;-)
wouldn't "sender" be the thread?

Author

Commented:
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.

TheRealLokiSenior Developer
CERTIFIED EXPERT

Commented:
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...
Top Expert 2007

Commented:
Top Expert 2007
Commented:
try like this

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

Author

Commented:
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.