标签:
分离状态的线程, 不能用pthread_join()等待它的终止状态.
例1: 修改属性, 创建分离状态线程
mypthread_attr_detach.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <pthread.h> //gcc -g mypthread_attr_detach.c -o mypthread_attr_detach -lpthread #define ERROR(flag,msg) if(flag) { printf("%d: ",__LINE__); fflush(stdout); perror(msg); exit(errno); } void print(char *s) { pid_t pid = getpid(); pthread_t tid = pthread_self(); printf("%s pid = %d, tid = %lu(0x%lx)\n", s, pid, tid, tid); } void *thread_func(void *arg) { int num; print("new thread"); sleep(1); printf("%lu thread &num = 0x%lx\n", (unsigned long)arg, (unsigned long)&num); return arg; } #define MAX_THREAD 5 int main(int argc, char *argv[]) { int i; int size; pthread_t tid[MAX_THREAD]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); for(i = 0; i < MAX_THREAD; i++) { int ret = pthread_create(&tid[i], &attr,thread_func, (void *)(long)i); ERROR(ret != 0,"pthread_create()"); } pthread_attr_destroy(&attr); print("main thread"); int ret; int stat[MAX_THREAD]; for(i = 0; i < MAX_THREAD; i++) { ret = pthread_join(tid[i], (void **)&stat[i]); if(ret != 0) { printf("pthread_join() fail!!! "); } printf("thread %lu(0x%lx) exit code = %d\n", tid[i], tid[i], stat[i]); } sleep(2); puts("byebye..."); return 0; }
编译链接运行, 输出如下:
对分离状态下的线程调用pthread_join()失败.
例2: 调用pthread_detach()使线程进入分离状态
mypthread_detach.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <pthread.h> //gcc -g mypthread_detach.c -o mypthread_detach -lpthread #define ERROR(flag,msg) if(flag) { printf("%d: ",__LINE__); fflush(stdout); perror(msg); exit(errno); } void print(char *s) { pid_t pid = getpid(); pthread_t tid = pthread_self(); printf("%s pid = %d, tid = %lu(0x%lx)\n", s, pid, tid, tid); } void *thread_func(void *arg) { int num; print("new thread"); sleep(1); printf("%lu thread &num = 0x%lx\n", (unsigned long)arg, (unsigned long)&num); return arg; } #define MAX_THREAD 5 int main(int argc, char *argv[]) { int i; int size; pthread_t tid[MAX_THREAD]; //pthread_attr_t attr; //pthread_attr_init(&attr); //pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); for(i = 0; i < MAX_THREAD; i++) { //int ret = pthread_create(&tid[i], &attr,thread_func, (void *)(long)i); int ret = pthread_create(&tid[i], NULL, thread_func, (void *)(long)i); ERROR(ret != 0,"pthread_create()"); pthread_detach(tid[i]); } //pthread_attr_destroy(&attr); print("main thread"); int ret; int stat[MAX_THREAD]; for(i = 0; i < MAX_THREAD; i++) { ret = pthread_join(tid[i], (void **)&stat[i]); if(ret != 0) { printf("pthread_join() fail!!! "); } printf("thread %lu(0x%lx) exit code = %d\n", tid[i], tid[i], stat[i]); } sleep(2); puts("byebye..."); return 0; }
编译链接执行, 输出如下:
对比将代码中的pthread_detach()注释掉后, 再编译链接执行, 输出如下:
标签:
原文地址:http://www.cnblogs.com/zhanglong71/p/5140415.html