Ryan
Ryan

Reputation: 2053

Must I detach or join a pthread?

The pthread_detach() documentation says:

The pthread_detach() function shall indicate to the implementation that storage for the thread thread can be reclaimed when that thread terminates.

What is the consequence if I create a joinable thread and do not detach or join it? The resources of that thread are not going to be reclaimed?

Upvotes: 4

Views: 1915

Answers (3)

Loki Astari
Loki Astari

Reputation: 264331

Just the resource associated with thread that are kept around for a join operation (ie the status code and a tiny bit more).

"Detached" just means I am not going to call join on this thread so cleanup the thread specific data when the thread is done (that would have been done by calling join).

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254421

That's right; you'll leak resources if you neither join nor detach a thread.

Each thread will allocate some memory for its stack, and probably some control structures, and this memory won't be freed. On some operating systems, there is a limit to the number of threads you can launch, and you may eventually get to a state where you can't launch any more.

Upvotes: 2

James Kanze
James Kanze

Reputation: 153889

You answered your own question? A thread requires certain resources in the system. These will be kept until either the thread is joined, or it is detached and it terminates. (Until you detach the thread, the system must suppose that you will join it sometime in the future, and cannot free the resources.)

Upvotes: 3

Related Questions