pthread_detchhas例子
时间: 2023-06-27 13:07:32 浏览: 51
pthread_detach函数用于将线程设置为“可分离的”状态,这意味着当线程退出时,它的资源会自动被回收,而不需要其他线程调用pthread_join函数来等待它的退出。
以下是一个使用pthread_detach函数的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_func(void *arg) {
printf("Thread running...\n");
pthread_detach(pthread_self());
printf("Thread detached...\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread;
if (pthread_create(&thread, NULL, thread_func, NULL) != 0) {
printf("Error creating thread.\n");
return 1;
}
printf("Thread created.\n");
sleep(1);
printf("Main thread exiting...\n");
return 0;
}
```
在上述代码中,主线程创建了一个新的线程,并将其设置为可分离状态。线程函数中使用pthread_detach函数将自己设置为可分离状态,然后调用pthread_exit函数退出。主线程等待1秒钟后退出,此时新线程可能仍在运行,但它的资源会自动被回收。
注意,在使用pthread_detach函数时,必须确保线程已启动并且没有被其他线程join。否则,调用pthread_detach函数可能会失败并返回错误码。