现在的位置: 首页 > 综合 > 正文

call pthread_join() or pthread_detach() for every thread

2012年06月20日 ⁄ 综合 ⁄ 共 2554字 ⁄ 字号 评论关闭
文章目录

http://java.icmc.usp.br/resources/books/ibm_pthreads/users-16.htm

pthread_detach()--Detach a Thread


Syntax

#include <pthread.h>
            int pthread_detach(pthread_t thread);
            Threadsafe: Yes
            Signal Safe: No
            

The pthread_detach() function indicates that system resources for the specified thread should be reclaimed when the thread ends. If the thread is already ended, resources are reclaimed immediately. This routine does not cause the thread to end. After pthread_detach() has been issued, it is not valid to try to pthread_join() with the target thread.

Eventually, you should call pthread_join() or pthread_detach() for every thread that is created joinable (with a detachstate of PTHREAD_CREATE_JOINABLE) so that the system can reclaim all resources associated with the thread. Failure to join to or detach joinable threads will result in memory and other resource leaks until the process ends.

If thread doesn't represent a valid undetached thread, pthread_detach() will return ESRCH.

Parameters

thread

(Input) Pthread handle to the target thread

Authorities and Locks

None.

Return Value

0

pthread_detach() was successful.

value

pthread_detach() was not successful. value is set to indicate the error condition.

Error Conditions

If pthread_detach() was not successful, the error condition returned usually indicates one of the following errors. Under some conditions, the value returned could indicate an error other than those listed here.

[EINVAL]

The value specified for the argument is not correct.

[ESRCH]

No item could be found that matches the specified value

Related Information

Example

#define _MULTI_THREADED
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "check.h"
void *threadfunc(void *parm)
{
printf("Inside secondary thread\n");
return NULL;
}
int main(int argc, char **argv)
{
pthread_t             thread;
int                   rc=0;
printf("Enter Testcase - %s\n", argv[0]);
printf("Create thread using attributes that allow join or detach\n");
rc = pthread_create(&thread, NULL, threadfunc, NULL);
checkResults("pthread_create()\n", rc);
sleep(5);
printf("Detach the thread after it terminates\n");
rc = pthread_detach(thread);
checkResults("pthread_detach()\n", rc);
printf("Detach the thread again (expect ESRCH)\n");
rc = pthread_detach(thread);
if (rc != ESRCH) {
printf("Got an unexpected result! rc=%d\n",
rc);
exit(1);
}
printf("Second detach fails correctly\n");
/* sleep() isn't a very robust way to wait for the thread */
sleep(5);
printf("Main completed\n");
return 0;
}

Output

Enter Testcase - QP0WTEST/TPDET0
Create thread using attributes that allow join or detach
Inside secondary thread
Detach the thread after it terminates
Detach the thread again (expect ESRCH)
Second detach fails correctly
Main completed

抱歉!评论已关闭.