单个线程在不终止整个进程的情况下停止他的控制流
(1). 线程从启动例程中返回,返回值是线程的退出码
(2). 线程可以被统一进程中的其他线程取消
(3). 线程调用pthread_exit.
获取线程退出状态:
#include <unistd.h>
#include <pthread.h>
void* thr_fn1(void* arg)
{
printf("thread 1 returning\n");
return ((void *)1);
}
void* thr_fn2(void* arg)
{
printf("thread 2 exiting\n");
return ((void*)2);
}
int main()
{
int err;
pthread_t tid1, tid2;
void* tret;
err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if(err != 0)
{
printf("can't create pthread 1: %s\n", strerror(err));
}
err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if(err != 0)
{
printf("can't create pthread 2: %s\n", strerror(err));
}
err = pthread_join(tid1, &tret);
if(err != 0)
{
printf("can't join with thread 1: %s\n", strerror(err));
}
printf("thread 1 exit code %d\n", (int)tret);
err = pthread_join(tid2, &tret);
if(err != 0)
{
printf("can't join with thread 2: %s\n", strerror(err));
}
printf("thread 2 exit code %d\n", (int)tret);
exit(0);
}
#include <unistd.h> 2 #include <stdio.h> 3 #include <pthread.h> 4 5 struct foo 6 { 7 int a, b, c, d; 8 }; 9 10 11 void printfoo(const char *s, const struct foo *fp) 12 { 13 printf(s); 14 printf(" structure at 0x%x\n", (unsigned)fp); 15 printf(" foo.a = %d\n", fp->a); 16 printf(" foo.b = %d\n", fp->b); 17 printf(" foo.c = %d\n", fp->c); 18 printf(" foo.d = %d\n", fp->d); 19 } 20 21 void thr_fn1(void* arg) 22 { 23 struct foo foo = {1, 2, 3, 4}; 24 printfoo("thread 1:\n", &foo); 25 pthread_exit((void*)&foo); 26 } 27 28 void thr_fn2(void* arg) 29 { 30 printf("thread 2: ID is %d\n", pthread_self()); 31 pthread_exit((void*)0); 32 } 34 int main() 35 { 36 int err; 37 pthread_t tid1, tid2; 38 struct foo* fp; 39 40 err = pthread_create(&tid1, NULL, thr_fn1, NULL); 41 if(err != 0) 42 { 43 printf("can't create thread 1: %s\n", strerror(err)); 44 } 45 err = pthread_join(tid1, (void*)&fp); 46 47 if(err != 0) 48 { 49 printf("can't join with thread 1: %s\n", strerror(err)); 50 } 51 52 sleep(1); 53 printf("parent starting second pthread\n"); 54 err = pthread_create(&tid2, NULL, thr_fn2, NULL); 55 if(err != 0) 56 { 57 printf("can't join with thread 2: %s\n", strerror(err)); 58 } 59 sleep(1); 60 61 printfoo("parent :\n", fp); 62 63 exit(0); 64 65 }