Reputation: 462
I've got a setup something a bit like this:
void* work(void*) { while (true) {/*do work*/} return 0;}
class WorkDoer
{
private:
pthread_t id;
public:
WorkDoer() { pthread_create(&id, NULL, work, (void*)this); }
void Shutdown() { pthread_join(id, NULL); /*other cleanup*/ }
}
There's some cases where Shutdown()
is called from the main thread, and some other cases where I want to call shutdown from within the thread itself (returning from that thread right after).
The documentation for pthread_join()
says that it will return a EDEADLK
if the calling thread is the same as the one passed.
My question is: Is that an okay thing to do, and if so is it safe? (thus ignoring the join fail, because I'll be nicely ending the thread in a moment anyways?) Or, is it something that should be avoided?
Upvotes: 2
Views: 4005
Reputation:
You can certainly call pthread_join()
from the running thread itself, and as you have found out the call itself will handle it properly giving you an error code. However, there are a few problems:
pthread_join()
on itself.pthread_join()
unless the thread was created as “detached”.So in other words this approach is as acceptable as a bug in your program.
As a solution I would recommend to revisit the design and make sure that Shutdown()
is called from the right place and at the right time. After all, the name “shutdown” doesn't make a lot of sense here because it doesn't shutdown a thing. What it does is merely waiting for a thread to finish and cleans up its state after that happens.
When you want to end the worker thread, either return from the thread routine or call pthread_exit()
. Then make sure that whoever started a thread cleans things up by calling pthread_join()
.
If you want to force the thread to stop, consider using pthread_kill()
to signal a thread or, alternatively, implement some sort of message passing that you can use to "tell" thread to stop doing whatever it is doing.
Upvotes: 5
Reputation: 70941
Why not just let the thread call pthread_detach(pthread_self());
and then exit. No need to call pthread_join()
then anymore and risking to have it fail.
Upvotes: 1
Reputation: 4245
The pthread_join() function may fail if:
EDEADLK
A deadlock was detected or the value of thread specifies the
calling thread.
I would say use at your own risk.
Upvotes: 1