线程终止的方式

单个线程在不终止整个进程的情况下停止他的控制流

(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 }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值