0xF1
0xF1

Reputation: 6116

Is it correct to detach a thread by itself anywhere in the program?

I am writing a multithread server program which echoes back data sent by clients. I am spawning one thread per client. Inside the thread's start routine, I am receiving client's data and echoing it back.

If client disconnects, then I am setting that thread as detached using pthread_detach(pthread_self()), so that on exit, the storage for the thread can be reclaimed as given here.

So I wanted to ask this:
1) Is it correct to detach a thread by itself?
2) Is it right to set thread as detached (by itself) anywhere in the program, i.e. is it not necessary to do so just after or at the time of creating the thread?

P.S.: My program is working fine, but since, in a multithreaded program, even if errors are there, they may not show up initially, so I wanted to clear these two problems.

Upvotes: 3

Views: 2765

Answers (3)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215597

Whether it's correct for a thread to detach itself is a matter of your program's contracts for resource ownership. If you want an analogy, pthread_detach and pthread_join are to pthread_t as free is to pointers obtained by malloc, or as close is to file descriptors. Having a thread call pthread_detach on itself is therefore much like having a function that behaves as a method for an object call free on the object. It's not inherently wrong, but it's fairly non-idiomatic and may be confusing to callers. If nothing else, you must document as part of your code's interface that the caller cannot use pthread_join on the thread, and if the caller needs a mechanism for determining when the thread's work is finished, you must provide another mechanism.

Upvotes: 1

Ashwani
Ashwani

Reputation: 3491

There is no problem in detaching thread by itself, but it should be take care that thread is detached correctly and no one have access to it after thread is detached. Destroy the object thread getting thread::id so that no variable can persist and make sure no other running thread has access to it after thread is detached. In normal conditions it is good to detach thread by itself

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477600

Every thread must be either joined or detached, and precisely one of these must happen for every successfully started thread. How and when you do that is entirely up to you.

Question 2 doesn't make a lot of sense: the thread only executes while it executes (tautologically), and you can only call functions while it executes. So a thread can detach itself whilte is still running, but of course not afterwards (since it's no longer running).

Upvotes: 2

Related Questions