当前位置: 首页 > news >正文

Linux 创建 终止线程(thread)

进程线程区别

创建线程

#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

    -功能:创建一个子线程,一般情况下main函数所在的线程称为主线程,其余的为子线程。

    -参数:

        -thread:传出参数,线程创建成功后,子线程的ID被写入这个变量

        -attr:设置线程的属性,一般使用默认值,NULL

        -start_routinue:函数指针,这个函数是子线程需要处理的函数

        -arg:给第三个参数使用,传参

    -返回值:

        - 成功:0

        -失败:返回错误号,和之前的错误号errno不太一样

        -获取错误的信息: char * strerror(int errnum)

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<pthread.h>
#include<string.h>void * callback(void * arg) {printf("child thread");return NULL;
}int main(){pthread_t tid;int ret = pthread_create(&tid, NULL, callback, NULL);if(ret != 0) {char * errstr = strerror(ret);printf("error: %s\n", errstr);}for(int i = 0; i < 5; i++) {printf("%d\n", i);}sleep(1);return 0;
}

终止进程

/*#include <pthread.h>void pthread_exit(void *retval);功能:终止一个线程,在哪个线程中调用,终止哪个参数:retval:传递一个指针,作为一个返回值,可以在pthread_join()中获取到int pthread_equal(pthread_t t1, pthread t2);功能:比较两个线程ID是否相等不同的操作系统实现pthread_t类型的方式不同,有的是无符号的长整型,有的是结构体
*/
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<unistd.h>void * callback(void* arg) {printf("child thread id %ld\n", pthread_self());return NULL;
}int main() {pthread_t tid;int ret = pthread_create(&tid, NULL, callback, NULL);if(ret != 0) {char * strerr = strerror(ret);printf("error:%s\n", strerr);}for(int i = 0; i < 5; i++) {printf("%d\n", i);}printf("child thread id %ld, main tid: %ld\n", tid, pthread_self());//主线程退出,其他线程不受影响pthread_exit(NULL);return 0;
}

http://www.lryc.cn/news/177679.html

相关文章:

  • 【IPC 通信】信号处理接口 Signal API(6)
  • ipaguard界面概览
  • 萌新的FPGA学习绪论-1
  • 目标检测算法改进系列之Backbone替换为EMO
  • Laravel一些优雅的写法
  • vue+three.js中使用Ammo.js
  • 【k8s】kubectl命令详解
  • Centos 7 部署SVN服务器
  • SEO方案尝试--Nuxtjs项目基础配置
  • 【算法分析与设计】动态规划(上)
  • Java多线程篇(6)——AQS之ReentrantLock
  • 【计算机网络】IP协议第二讲(Mac帧、IP地址、碰撞检测、ARP协议介绍)
  • TouchGFX界面开发 | 按钮控件应用示例
  • BSVD论文理解:Real-time Streaming Video Denoising with Bidirectional Buffers
  • 共同见证丨酷雷曼武汉运营中心成立2周年
  • 一种单键开关机电路图
  • 设计模式2、抽象工厂模式 Abstract Factory
  • C++ 32盏灯,利用进制和 与 或 进行设计
  • Ffmpeg-(1)-安装:ubuntu系统安装Ffmpeg应用
  • 系统集成|第十一章(笔记)
  • 二叉树题目:二叉树剪枝
  • JAVA中使用CompletableFuture进行异步编程
  • uniapp:配置动态接口域名,根据图片访问速度,选择最快的接口
  • Lambda表达式常见用法(提高效率神器)
  • 2023旷视自驾感知算法暑期实习一面
  • Python3 如何实现 websocket 服务?
  • SQLAlchemy常用数据类型
  • Vue路由与nodejs下载安装及环境变量的配置
  • HarmonyOS之 应用程序页面UIAbility
  • 数据集笔记: Porto