LinuxC多线程编程第二篇:线程终止
来源:互联网 发布:淘宝网客服联系打不开 编辑:程序博客网 时间:2024/05/21 10:21
终止线程可以有三种方法
1、线程回调函数return。这种方法对主线程不适合。
2、一个线程调用pthread_cancel将终止同一进程中的另一个线程(这个比较复杂,这里先不做介绍)
3、线程可以调用phtread_exit终止自己。
下面来看看pthread_exit与pthread_join用法:
#include <pthread.h>
void pthread_exit(void *value_ptr);
其它线程调用pthread_join获得这个指针,下面函数的第二个函数,呵呵。
#include <pthread.h>
int pthread_join(pthread_t thread, void **value_ptr);
通过上面的这个讲解,我觉得现在很有必要把终止线程的三种方法和pthread_join(pthread_t thread, void **value_ptr)中的value_ptr结合起来讲解。
1、首先thread线程通过return返回,value_ptr所指向的单元里存放的是thread线程函数的返回值。
2、pthread_cancel我先不做介绍,下面看个例子即可。
3、如果thread线程是自己调用pthread_exit终止的,value_ptr所指向的单元存放的是传给pthread_exit的参数。
#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <unistd.h>void *thr_return(void *arg){ printf("thread 1 returning\n"); sleep(10); return (void *)1;}void *thr_exit(void *arg){ printf("thread 2 exiting\n"); pthread_exit((void *)2);}void *thr_cancel(void *arg){ while(1) { printf("thread 3 writing\n"); sleep(1); }}int main(void){ pthread_t tid; void *tret; pthread_create(&tid, NULL, thr_return, NULL); pthread_join(tid, &tret); printf("thread 1 exit code %d\n", (int)tret); pthread_create(&tid, NULL, thr_exit, NULL);pthread_join(tid, &tret); printf("thread 2 exit code %d\n", (int)tret); pthread_create(&tid, NULL, thr_cancel, NULL); sleep(3); pthread_cancel(tid); pthread_join(tid, &tret); printf("thread 3 exit code %d\n", (int)tret); return 0;}
编译运行结果如下:
注意:
pthread_exit或者return返回的指针所指向的内存单元必须是全局的或者是用malloc分配的,不能在线程函数的栈上分配,因 为当其它线程得到这个返回值时线程函数已经结束了。
- LinuxC多线程编程第二篇:线程终止
- LinuxC多线程编程第二篇:线程终止
- LinuxC多线程编程第四篇:线程同步mutex
- LinuxC多线程编程第五篇:线程通信(Condition)
- LinuxC多线程编程第四篇:线程同步mutex
- LinuxC多线程编程第五篇:线程通信(Condition)
- C#多线程编程实战(从入门到精通系列)第二篇 指定间隔终止线程
- LinuxC多线程编程第一篇:线程创建
- LinuxC多线程编程第一篇:线程创建
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- java多线程编程--如何终止一个线程
- 多线程编程-线程的创建和终止
- 多线程编程之终止pthread线程
- chapter5 制作网页
- chapter6 网站设计和页面布局
- chapter7 网站设计和页面布局(二)
- chapter8 other
- Open SSH 基础
- LinuxC多线程编程第二篇:线程终止
- system.map
- QCon北京2012第三天记录
- 嵌入式-C语言面试题【转】
- LinuxC多线程编程第三篇:pthread_join与phread_datach介绍
- uploadify file null 为空 空值 uploadify-v3.0.1
- 位操作实现的加法算法
- LinuxC多线程编程第四篇:线程同步mutex
- 在苦逼的世界,苦逼的活着