标签:
#include <pthread.h>
int pthread_create(pthread_t *thread,const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
void *func(void *arg) { printf("pthread start\n"); return NULL; } int main(int arg, char * args[]) { pthread_t thr_d; int err = pthread_create(&thr_d, NULL, func, NULL); if (err != 0) { printf("create pthread failed\n"); } else { printf("create pthread success\n"); } sleep(1); return 0; }
void pthread_exit(void *arg);
arg是个无类型指针,该指针会被其他线程调用pthread_join捕捉。
void *func(void *arg) { printf("pthread start\n"); static int i = 1; pthread_exit(&i); } int main(int arg, char * args[]) { pthread_t thr_d; pthread_create(&thr_d, NULL, func, NULL); sleep(1); return 0; }
void *func(void *arg) { printf("pthread start\n"); static int i = 0; sleep(2); pthread_exit(&i); } int main(int arg, char * args[]) { pthread_t thr_d; pthread_create(&thr_d, NULL, func, NULL); void *p; pthread_join(thr_d, &p); int *pi = (int *)p; printf("thread exit %d\n", *pi); return 0; }
void *func(void *arg) { printf("pthread start\n"); pthread_exit(NULL); } int main(int arg, char * args[]) { pthread_t thr_d; pthread_create(&thr_d, NULL, func, NULL); pthread_detach(thr_d); sleep(1); return 0; }
void *func(void *arg) { printf("pthread start\n"); while(1) { printf("thread is running\n"); sleep(1); } pthread_exit(NULL); } int main(int arg, char * args[]) { pthread_t thr_d; pthread_create(&thr_d, NULL, func, NULL); pthread_detach(thr_d); sleep(6); pthread_cancel(thr_d); sleep(6); printf("end\n"); return 0; }
int pthread_attr_destroy(pthread_attr_t *attr);
int pthread_attr_init(pthread_attr_t *attr);
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate); 。
值 |
说明 |
PTHREAD_CREATE_DETACHED |
设置线程为分离状态 |
PTHREAD_CREATE_JOINABLE |
设置线程为正常状态 |
void *func(void *arg) { printf("pthread start\n"); while(1) { printf("thread is running\n"); sleep(1); } pthread_exit(NULL); } int main(int arg, char * args[]) { pthread_t thr_d; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&thr_d, &attr, func, NULL); pthread_attr_destroy(&attr); sleep(2); printf("end\n"); return 0; }
标签:
原文地址:http://www.cnblogs.com/shichuan/p/4496160.html