首页 技术 正文
技术 2022年11月20日
0 收藏 652 点赞 4,726 浏览 1078 个字

37.1 线程清理和控制函数

 #include <pthread.h> void pthread_cleanup_push(void (* rtn)(void *), void *arg);
void pthread_cleanup_pop(int execute);
  • 函数参数

    • rtn:清理函数指针
    • arg:调用清理函数传递的参数
    • execute:值 1 时,执行线程清理函数;值 0 时,不执行线程清理函数
  • 返回值
    • 成功,返回 0;否则,返回错误编号
  • 触发线程调用清理函数的工作
    • 调用 pthread_exit
    • 响应取消请求
    • 用非零 execute 参数调用 thread_cleanup_pop 时
 #include <stdio.h>
#include <stdlib.h>
#include <pthread.h> /** 定义线程清理函数 */
void clean_fun(void *arg)
{
char *s = (char *)arg;
printf("clean_fun: %s\n", s);
} void *th_fun(void *arg)
{
int execute = (int )arg; pthread_cleanup_push(clean_fun, "first clean func");
pthread_cleanup_push(clean_fun, "second clean func");
printf("thread running %lx\n", pthread_self()); pthread_cleanup_pop(execute);
pthread_cleanup_pop(execute);
return (void *);
} int main(void)
{
int err;
pthread_t th1, th2; if((err = pthread_create(&th1, NULL, th_fun, (void *))) != ) {
perror("pthread create error");
} pthread_join(th1, NULL);
printf("th1(%lx) finished\n", th1); if((err = pthread_create(&th2, NULL, th_fun, (void *))) != ) {
perror("pthread create error");
} pthread_join(th2, NULL);
printf("th2(%lx) finished\n", th2); return ;
}

  运行如下:

  三十七、Linux 线程——线程清理和控制函数、进程和线程启动方式比较、线程的状态转换

  线程结束,会触发调用最终的 clean 函数,调用的时候会根据 pop 里面的入栈顺序,先入后出进行调用。

37.2 进程和线程启动方式比较

  三十七、Linux 线程——线程清理和控制函数、进程和线程启动方式比较、线程的状态转换

37.3 线程的状态转换

  三十七、Linux 线程——线程清理和控制函数、进程和线程启动方式比较、线程的状态转换

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898