Linux线程创建及资源回收

创建一个线程并等待线程结束并回收资源

示例:create.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

static void rountine(void *str) //钩子函数
{
puts(str);
}

static void *func(void *p)  //线程调用函数
{
  puts("the thread is running");

  pthread_cleanup_push(rountine,"rounine running");  //线程压栈钩子函数
  pthread_cleanup_pop(1);  //线程退出时钩子函数出栈   1、执行钩子函数   0、不执行

  pthread_exit(NULL);  //线程退出函数
}

int main()
{
  pthread_t tid;
  int err;

  puts("Begin");

  err = pthread_create(&tid,NULL,func,NULL);  //创建线程无参数、保持默认属性
  if(err)
  {
    fprintf(stderr,"pthread_create():%s\n",strerror(err));
    exit(1);
  }

  puts("End");
  pthread_join(tid,NULL);  //等待线程结束收尸
  exit(0);
}

编译文件:Makefile

CFLAGS +=-pthread
LDFLAGS +=-pthread

 

posted @   *^VV^*  阅读(125)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示