#include <stdio.h>
void* thread_func(void* arg) {
printf(“Hello from the detached thread!\n”);
return NULL;
}
int main() {
pthread_t thread;
// 创建线程
if(pthread_create(&thread, NULL, thread_func, NULL)) {
fprintf(stderr, “Error creating thread\n”);
return 1;
}
// 将线程设置为分离状态
if(pthread_detach(thread)) {
fprintf(stderr, “Error detaching thread\n”);
return 2;
}
// 主线程执行
printf(“Hello from the main thread!\n”);
// 主线程休眠一段时间,以确保分离线程有足够的时间运行
sleep(1);
return 0;
}
在这个例子中,我们创建了一个线程并立即将其设置为分离状态。主线程并没有调用`pthread_join`来等待这个线程,因为分离的线程在结束时会自动清理它们自己。
需要注意的是,你只能分离一个线程一次。如果一个线程已经被分离,或者已经被另一个线程回收(通过`pthread_join`