To explicitly create a thread as joinable or detached, the attr argument in the pthread_create() routine
is used. The typical 4 step process is:
- Declare a pthread attribute variable of the pthread_attr_t data type
- Initialize the attribute variable with pthread_attr_init()
- Set the attribute detached status with pthread_attr_setdetachstate()
- When done, free library resources used by the attribute with pthread_attr_destroy()
/**
* NAME
* pthread_join - wait for thread termination
* SYNOPSIS
* #include <pthread.h>
* int pthread_join(pthread_t thread, void **value_ptr);
* DESCRIPTION
* The pthread_join() function shall suspend execution of the calling
* thread until the target thread terminates, unless the target thread has
* already terminated. On return from a successful pthread_join() call
* with a non-NULL value_ptr argument, the value passed to pthread_exit()
* by the terminating thread shall be made available in the location ref-
* erenced by value_ptr. When a pthread_join() returns successfully, the
* target thread has been terminated. The results of multiple simultaneous
* calls to pthread_join() specifying the same target thread are unde-
* fined. If the thread calling pthread_join() is canceled, then the tar-
* get thread shall not be detached.
* It is unspecified whether a thread that has exited but remains unjoined
* counts against {PTHREAD_THREADS_MAX}.
* RETURN VALUE
* If successful, the pthread_join() function shall return zero; other-
* wise, an error number shall be returned to indicate the error.
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
//线程执行的函数
void *BusyWork(void *t)
{
int i;
long tid;
double result = 0.0;
tid = (long) t;
printf("Thread %ld starting...\n", tid);
for (i = 0; i < 1000000; i++)
{
result = result + sin(i) * tan(i);
}
printf("Thread %ld done. Result = %e\n", tid, result);
pthread_exit((void*) t);
return NULL ;
}
int main(int argc, char *argv[])
{
pthread_t thread[NUM_THREADS];
//定义pthread_attr_t变量
pthread_attr_t attr;
int rc;
long t;
void *status;
/* Initialize and set thread detached attribute */
/**
* 主要注意一下两个方法
* 初始化attr
* pthread_attr_init
* 设置这个线程是可以joinable
* pthread_attr_setdetachstate
*/
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (t = 0; t < NUM_THREADS; t++)
{
printf("Main: creating thread %ld\n", t);
//主要是函数的第二个参数
//把设置好的attr传入
rc = pthread_create(&thread[t], &attr, BusyWork, (void *) t);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Free attribute and wait for the other threads */
//释放attribute
pthread_attr_destroy(&attr);
for (t = 0; t < NUM_THREADS; t++)
{
rc = pthread_join(thread[t], &status);
if (rc)
{
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
printf("Main: completed join with thread %ld having a status of %ld\n",
t, (long) status);
}
printf("Main: program completed. Exiting.\n");
pthread_exit(NULL );
}