Can a thread delete itself?

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; }

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.

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.

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.

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.

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