Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the usage of PTHREAD_CREATE_JOINABLE in pthread?

Tags:

c

pthreads

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?

like image 315
injoy Avatar asked Aug 04 '12 07:08

injoy


People also ask

What is Pthread_create_joinable?

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.

What is difference between Pthread_create_joinable and Pthread_create_detached?

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.

What is Pthread_detach used for?

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.

What is the use of pthread_join?

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.


2 Answers

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.

like image 112
che Avatar answered Oct 06 '22 10:10

che


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.

like image 23
Stephane Rouberol Avatar answered Oct 06 '22 10:10

Stephane Rouberol