Can a thread delete itself?


#1

I want my threads to delete themselves when they are done, but this doesn’t seem possible.

I’m doing something like this, but it throws an exception.

Thread* t = new MyThread();
t->startThread();

void MyThread::run() { // do work delete this; }


#2

No, it needs to do a bunch of housekeeping when the run method returns, so the object has to still exist.

Why not use a thread pool? That will close the thread when all its jobs complete.

Or make the object an asyncupdater, trigger an update when the thread finishes, and delete the object in the async callback.


#3

The answer lies in Thread::threadEntryPoint (Thread* thread). Look at the last two lines of code:

thread->threadHandle_ = 0;
thread->threadId_ = 0;

Since you’ve already deleted the thread, thread points to nothing. That’s why you get an exception. [Edit] Plus all the housekeeping stuff Jules mentioned above [/Edit]

You should redesign so that you don’t have a thread for each thing you need to do, rather have a thread call jobs. Look at ThreadPool and ThreadPoolJob.


#4

I’ll just do the asyncupdater method. The ThreadPool is almost what I need, except I can’t change the number of threads once it’s created.


#5

What about adding a virtual function to thread:

And calling it from the last line of threadEntryPoint

Threads could override it to delete themselves, or whatever else they might want to do after then have finished running.


#6

Not sure I like the sound of that! Feels a bit wrong, somehow, though I can’t think of a good argument against it!


#7