Reputation:
I'm new to C and multithread programming, just some question on detached threads. Below is some sample code from my textbook:
#define NTHREADS 4
int main(int argc, char **argv) {
...
for (i = 0; i < NTHREADS; i++) /* Create worker threads */
pthread_create(&tid, NULL, thread, NULL);
while (1) {
...// main thread produce repeatedly produces new items and inserts them in a shared buffer that will be consumed by the worker threads
}
}
void *thread(void *vargp) {
pthread_detach(pthread_self());
while (1) {
...// worker thread consumes the item from the shared buffer.
}
}
My question is, why worker thread needs to call pthread_detach(pthread_self());
? becuase there is an infinite while loop below, so there is no need for itself to be reaped automatically since it never stop?
Upvotes: 1
Views: 95
Reputation: 182885
That would be part of the code that cleans up the thread or prepares the process for shutdown. Since that code is not present and there is no way to cleanly shut anything down, it makes no difference whether the call is there or not. The thread can never terminate or be joined anyway, so it makes no difference whether or not it's detached.
Upvotes: 1