pthread_detach使用实例
时间: 2024-01-06 11:06:51 浏览: 99
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");
return NULL;
}
int main() {
pthread_t thread;
int ret;
ret = pthread_create(&thread, NULL, thread_func, NULL);
if (ret != 0) {
printf("Failed to create thread\n");
return 1;
}
ret = pthread_detach(thread);
if (ret != 0) {
printf("Failed to detach thread\n");
return 1;
}
// 主线程继续执行其他任务
printf("Main thread continues\n");
// 等待一段时间,让分离状态的线程有足够时间执行完毕
sleep(2);
printf("Main thread exits\n");
return 0;
}
```
在上述示例中,首先创建了一个新的线程,并使用pthread_create()函数将其设置为可执行线程。然后,使用pthread_detach()函数将该线程设置为分离状态。
接着,主线程继续执行其他任务,并等待一段时间,让分离状态的线程有足够的时间执行完毕。最后,主线程退出并结束程序。
当运行上述代码时,你会看到输出类似于:
```
Thread running
Main thread continues
Main thread exits
```
可以看到,分离状态的线程在主线程退出后仍能继续执行,无需其他线程调用pthread_join()函数来等待其结束。
阅读全文
相关推荐


















