thread_cleanup

线程清理机制在C++中的应用
本文探讨了在C++中使用pthread库进行线程清理操作的实践,通过定义清理函数并推入线程上下文,实现线程结束后自动执行清理任务,确保资源的正确释放。

 

// void pthread_cleanup_push(void (*routine)(void*), void *arg);
// void pthread_cleanup_pop(int execute);
//
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>


static void cleanup_func(void *p)
{
 puts(p);
}

static void *func(void *p)
{
 puts("Thread is working!");
 pthread_cleanup_push(cleanup_func,"cleanup:1");
 pthread_cleanup_push(cleanup_func,"cleanup:2");
 pthread_cleanup_push(cleanup_func,"cleanup:3");
// 
// 实现方式为宏,并且以配对的形式出现
 pthread_cleanup_pop(1);
 pthread_cleanup_pop(1);
 pthread_cleanup_pop(0);
//
 pthread_exit(NULL);//先结束线程,不能调用清理处理程序
}

int main()
{
 int err;
 pthread_t tid;

 puts("Begin!");

 err = pthread_create(&tid,NULL,func,NULL);
 if(err)
 {
  fprintf(stderr,"pthread_create():%s\n",strerror(err));
  exit(1);
 }

 pthread_join(tid,NULL);
 
 puts("End!");

 exit(0);
}

 

#include<stdio.h> #include<unistd.h> #include<pthread.h> void cleanup(void *arg){ printf("cleanup,arg=%s\n",(char *)arg); } void *func (void *arg) { printf("this is child pthread\n"); // pthread_exit("pthread return\n"); phtread_cleanup_push(cleanup,"abcd"); while(1){ sleep(1); } pthread_exit("thread return"); pthread_cleanup_pop(1); } int main (){ pthread_t tid; void *retv; pthread_create(&tid,NULL,func,NULL); sleep(1); pthread_cancel(tid); pthread_join(tid,&retv); // printf("thread ret=%s\n",(char *)retv); while(1){ sleep(1); } } 我在Ubuntu运行代码时处出现一下报错请你帮我指出并修改: root@ubuntu:~/jincheng/day4# gcc -o cleanup cleanup.c -lpthread cleanup.c: In function ‘func’: cleanup.c:12:2: warning: implicit declaration of function ‘phtread_cleanup_push’ [-Wimplicit-function-declaration] phtread_cleanup_push(cleanup,"abcd"); ^ In file included from cleanup.c:3:0: cleanup.c: At top level: cleanup.c:17:2: error: expected identifier or ‘(’ before ‘while’ pthread_cleanup_pop(1); ^ cleanup.c:17:2: error: expected declaration specifiers or ‘...’ before ‘&’ token pthread_cleanup_pop(1); ^ cleanup.c:17:2: error: expected identifier or ‘(’ before ‘if’ pthread_cleanup_pop(1); ^ cleanup.c:17:2: error: expected identifier or ‘(’ before ‘}’ token pthread_cleanup_pop(1); ^ cleanup.c:17:2: error: expected identifier or ‘(’ before ‘while’ pthread_cleanup_pop(1); ^ cleanup.c:19:1: error: expected identifier or ‘(’ before ‘}’ token }
07-26
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值