LinuxC多线程编程第二篇:线程终止
来源:互联网 发布:sql create 唯一 编辑:程序博客网 时间:2024/05/17 09:03
分类: c/c++ 2012-04-21 06:17 1188人阅读 评论(0)收藏 举报
多线程编程threadjoinnullreturning
终止线程可以有三种方法
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分配的,不能在线程函数的栈上分配,因 为当其它线程得到这个返回值时线程函数已经结束了。
0 0
- LinuxC多线程编程第二篇:线程终止
- LinuxC多线程编程第二篇:线程终止
- LinuxC多线程编程第四篇:线程同步mutex
- LinuxC多线程编程第五篇:线程通信(Condition)
- LinuxC多线程编程第四篇:线程同步mutex
- LinuxC多线程编程第五篇:线程通信(Condition)
- C#多线程编程实战(从入门到精通系列)第二篇 指定间隔终止线程
- LinuxC多线程编程第一篇:线程创建
- LinuxC多线程编程第一篇:线程创建
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- 多线程编程-线程的创建和终止
- java多线程编程--如何终止一个线程
- 多线程编程-线程的创建和终止
- 多线程编程之终止pthread线程
- 作为一个新人,怎样学习嵌入式Linux?
- POJ1019-Number Sequence
- 《C++ primer 5》 chapter 2.2
- php学习之道:php中iconv函数 详解
- 模块XXXX.dll已加载但对dllregisterserver的调用失败
- LinuxC多线程编程第二篇:线程终止
- 麻省理工算法导论公开课(2)
- httplib HTTP协议客户端实现
- Oracle Linux 4.7下配置udev
- getaddrinfo函数的说明
- LinuxC多线程编程第三篇:pthread_join与phread_datach介绍
- 利用SSH框架实现用户登录功能
- LinuxC多线程编程第四篇:线程同步mutex
- LinuxC多线程编程第五篇:线程通信(Condition)