c语言线程控制,2. 线程控制

2.2. 终止线程

如果需要只终止某个线程而不终止整个进程,可以有三种方法:

从线程函数return。这种方法对主线程不适用,从main函数return相当于调用exit。

一个线程可以调用pthread_cancel终止同一进程中的另一个线程。

线程可以调用pthread_exit终止自己。

用pthread_cancel终止一个线程分同步和异步两种情况,比较复杂,本章不打算详细介绍,读者可以参考[APUE2e]。下面介绍pthread_exit的和pthread_join的用法。#include

void pthread_exit(void *value_ptr);

value_ptr是void *类型,和线程函数返回值的用法一样,其它线程可以调用pthread_join获得这个指针。

需要注意,pthread_exit或者return返回的指针所指向的内存单元必须是全局的或者是用malloc分配的,不能在线程函数的栈上分配,因为当其它线程得到这个返回指针时线程函数已经退出了。#include

int pthread_join(pthread_t thread, void **value_ptr);

返回值:成功返回0,失败返回错误号

调用该函数的线程将挂起等待,直到id为thread的线程终止。thread线程以不同的方法终止,通过pthread_join得到的终止状态是不同的,总结如下:

如果thread线程通过return返回,value_ptr所指向的单元里存放的是thread线程函数的返回值。

如果thread线程被别的线程调用pthread_cancel异常终止掉,value_ptr所指向的单元里存放的是常数PTHREAD_CANCELED。

如果thread线程是自己调用pthread_exit终止的,value_ptr所指向的单元存放的是传给pthread_exit的参数。

如果对thread线程的终止状态不感兴趣,可以传NULL给value_ptr参数。

看下面的例子(省略了出错处理):#include

#include

#include

#include

void *thr_fn1(void *arg)

{

printf("thread 1 returning\n");

return (void *)1;

}

void *thr_fn2(void *arg)

{

printf("thread 2 exiting\n");

pthread_exit((void *)2);

}

void *thr_fn3(void *arg)

{

while(1) {

printf("thread 3 writing\n");

sleep(1);

}

}

int main(void)

{

pthread_t tid;

void *tret;

pthread_create(&tid, NULL, thr_fn1, NULL);

pthread_join(tid, &tret);

printf("thread 1 exit code %d\n", (int)tret);

pthread_create(&tid, NULL, thr_fn2, NULL);

pthread_join(tid, &tret);

printf("thread 2 exit code %d\n", (int)tret);

pthread_create(&tid, NULL, thr_fn3, NULL);

sleep(3);

pthread_cancel(tid);

pthread_join(tid, &tret);

printf("thread 3 exit code %d\n", (int)tret);

return 0;

}

运行结果是:$ ./a.out

thread 1 returning

thread 1 exit code 1

thread 2 exiting

thread 2 exit code 2

thread 3 writing

thread 3 writing

thread 3 writing

thread 3 exit code -1

可见在Linux的pthread库中常数PTHREAD_CANCELED的值是-1。可以在头文件pthread.h中找到它的定义:#define PTHREAD_CANCELED ((void *) -1)

一般情况下,线程终止后,其终止状态一直保留到其它线程调用pthread_join获取它的状态为止。但是线程也可以被置为detach状态,这样的线程一旦终止就立刻回收它占用的所有资源,而不保留终止状态。不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL。对一个尚未detach的线程调用pthread_join或pthread_detach都可以把该线程置为detach状态,也就是说,不能对同一线程调用两次pthread_join,或者如果已经对一个线程调用了pthread_detach就不能再调用pthread_join了。#include

int pthread_detach(pthread_t tid);

返回值:成功返回0,失败返回错误号。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值