I read some codes as below:
void
mcachefs_file_start_thread()
{
pthread_attr_t attrs;
pthread_attr_init(&attrs);
pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_JOINABLE);
pthread_create(&mcachefs_file_threadid, &attrs, mcachefs_file_thread, NULL);
}
Here, what is the usage of setting attrs
as PTHREAD_CREATE_JOINABLE
? Besides, isn't it the default attribute of a thread created by pthead_create
?
PTHREAD_CREATE_JOINABLE Threads that are created using attr will be created in a joinable state. The default setting of the detach state attribute in a newly initialized thread attributes object is PTHREAD_CREATE_JOINABLE.
The detachstate can be set to either PTHREAD_CREATE_DETACHED or PTHREAD_CREATE_JOINABLE. A value of PTHREAD_CREATE_DETACHED causes all threads created with attr to be in the detached state, whereas using a value of PTHREAD_CREATE_JOINABLE causes all threads created with attr to be in the joinable state.
The pthread_detach() function is used to indicate to your application that storage for the thread tid can be reclaimed when the thread terminates. Threads should be detached when they are no longer needed. If tid has not terminated, pthread_detach() does not cause the thread to terminate.
The pthread_join() function provides a simple mechanism allowing an application to wait for a thread to terminate. After the thread terminates, the application may then choose to clean up resources that were used by the thread.
Yes, PTHREAD_CREATE_JOINABLE
is the default attribute. The purpose is that it allows you to call pthread_join
on the thread, which is a function that waits until the thread finishes, and gives you return value if its main routine.
Sometimes, when you're creating a thread to do some background work, it might be a good idea to make sure it has finished before you use its results or move to something else. That's what joinable threads are for.
From posix spec, the default setting of the detach state attribute in a newly initialized thread attributes object is indeed PTHREAD_CREATE_JOINABLE. See for instance http://linux.die.net/man/3/pthread_attr_setdetachstate So you are right: the pthread_attr_setdetachstate line of code is not necessary in your code snippet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With