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

linux---多线程

  1. 线程的基本概念
    • 定义:在Linux中,线程是进程内部的一个执行单元,是进程的一个实体,它是CPU调度和分派的基本单位。一个进程可以包含多个线程,这些线程共享进程的资源,如代码段、数据段、打开的文件、信号处理函数等,但每个线程都有自己独立的栈空间和程序计数器(PC)。
    • 与进程的区别
      • 进程是资源分配的基本单位,每个进程都有独立的地址空间和系统资源。而线程是进程中的执行路径,共享进程的大部分资源,这使得线程间的通信和切换成本相对较低。
      • 进程间的切换需要进行系统调用,涉及到用户态和内核态的切换,开销较大。线程切换主要是在用户态下进行,只需要保存和恢复少量的寄存器内容和栈指针,速度更快。
  2. 线程库的选择 - pthread库
    • 简介:在Linux系统中,最常用的线程库是POSIX线程库(pthread)。它提供了一系列函数来创建、管理和同步线程。使用pthread库时,需要在编译时链接-lpthread选项。
  3. 线程的创建 - pthread_create函数
    • 函数原型int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
    • 参数说明
      • thread:这是一个指向pthread_t类型变量的指针,用于存储新创建线程的标识符。
      • attr:这是一个指向pthread_attr_t类型的指针,用于设置线程的属性,如线程的栈大小、调度策略等。如果为NULL,则使用默认属性创建线程。
      • start_routine:这是一个函数指针,指向线程的起始函数。线程创建成功后,会从这个函数开始执行。该函数的参数是一个void*类型的指针,返回值也是一个void*类型的指针。
      • arg:这是传递给start_routine函数的参数,通过void*类型的指针传递,可以传递任何类型的数据,在start_routine函数内部需要进行适当的类型转换。
    • 返回值
      • 成功时返回0,表示线程创建成功。
      • 失败时返回一个错误码,并且不会创建线程。可以通过strerror函数将错误码转换为对应的错误信息。
    • 示例代码(创建一个简单的线程)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 线程执行的函数
void *thread_function(void *arg) {// 在这里编写线程要执行的任务printf("这是一个新线程。\n");// 线程结束时返回NULLreturn NULL;
}
int main() {pthread_t thread_id;int result;// 创建线程result = pthread_create(&thread_id, NULL, thread_function, NULL);if (result!= 0) {// 如果创建线程失败,打印错误信息perror("线程创建失败");return 1;}// 主线程继续执行其他任务,这里简单地等待新线程结束result = pthread_join(thread_id, NULL);if (result!= 0) {perror("等待线程结束失败");return 1;}printf("主线程继续执行,线程已结束。\n");return 0;
}
  1. 线程的终止 - pthread_exit函数和其他方式
    • pthread_exit函数

      • 函数原型void pthread_exit(void *value_ptr);
      • 功能:用于显式地终止一个线程。当线程执行到pthread_exit函数时,线程会立即终止,并将value_ptr指向的值返回给等待该线程结束的线程(如果有)。这个返回值可以通过pthread_join函数获取。
        在这里插入图片描述
    • start_routine函数中return返回

      • 线程执行的起始函数start_routine执行return语句时,线程也会正常终止,返回值的处理方式和pthread_exit类似。
    • 线程被其他线程取消(pthread_cancel函数)

      • 函数原型int pthread_cancel(pthread_t thread);
      • 功能:一个线程可以通过pthread_cancel函数来请求取消另一个线程。被取消的线程会在合适的时机(如在某些系统调用中或者在检查取消点时)终止。不过,线程可以通过设置一些属性来控制是否响应取消请求以及如何响应。
  2. 线程的等待 - pthread_join函数
    • 函数原型int pthread_join(pthread_t thread, void **value_ptr);
    • 参数说明
      • thread:要等待的线程的标识符。
      • value_ptr:这是一个指向void*类型指针的指针,用于存储被等待线程的返回值(如果线程通过pthread_exit函数或者在start_routine函数中return返回了一个值)。如果不需要获取返回值,可以将这个参数设置为NULL
    • 返回值
      • 成功时返回0,表示成功等待线程结束并获取了返回值(如果需要获取)。
      • 失败时返回一个错误码,并且不会正确等待线程结束。
  3. 线程的同步 - 互斥锁(Mutex)
    • 基本概念
      • 互斥锁用于保护共享资源,防止多个线程同时访问和修改共享资源而导致数据不一致。互斥锁有两种状态:锁定和解锁。当一个线程获取了互斥锁(锁定状态)后,其他线程如果试图获取同一把互斥锁,就会被阻塞,直到该锁被释放(解锁状态)。
    • 互斥锁相关函数
      • pthread_mutex_init函数:用于初始化一个互斥锁。函数原型为int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);,其中mutex是指向pthread_mutex_t类型变量的指针,用于存储互斥锁,attr是指向互斥锁属性的指针,如果为NULL,则使用默认属性初始化。
      • pthread_mutex_lock函数:用于获取(锁定)互斥锁。函数原型为int pthread_mutex_lock(pthread_mutex_t *mutex);,如果互斥锁已经被其他线程锁定,调用该函数的线程会被阻塞,直到互斥锁被释放。
      • pthread_mutex_unlock函数:用于释放(解锁)互斥锁。函数原型为int pthread_mutex_unlock(pthread_mutex_t *mutex);,当一个线程完成对共享资源的访问后,应该及时释放互斥锁,以便其他线程可以获取。
      • pthread_mutex_destroy函数:用于销毁互斥锁。函数原型为int pthread_mutex_destroy(pthread_mutex_t *mutex);,在互斥锁不再使用时,应该销毁它,释放相关资源。
    • 示例代码(使用互斥锁保护共享资源)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 定义一个共享变量
int shared_variable = 0;
// 定义互斥锁
pthread_mutex_t mutex;
// 线程执行的函数
void *thread_function(void *arg) {int i;for (i = 0; i < 1000; ++i) {// 锁定互斥锁pthread_mutex_lock(&mutex);// 访问共享资源shared_variable++;// 解锁互斥锁pthread_mutex_unlock(&mutex);}return NULL;
}
int main() {pthread_t thread_id1, thread_id2;int result;// 初始化互斥锁result = pthread_mutex_init(&mutex, NULL);if (result!= 0) {perror("互斥锁初始化失败");return 1;}// 创建两个线程result = pthread_create(&thread_id1, NULL, thread_function, NULL);if (result!= 0) {perror("线程1创建失败");return 1;}result = pthread_create(&thread_id2, NULL, thread_function, NULL);if (result!= 0) {perror("线程2创建失败");return 1;}// 等待线程结束result = pthread_join(thread_id1, NULL);if (result!= 0) {perror("等待线程1结束失败");return 1;}result = pthread_join(thread_id2, NULL);if (result!= 0) {perror("等待线程2结束失败");return 1;}// 销毁互斥锁result = pthread_mutex_destroy(&mutex);if (result!= 0) {perror("互斥锁销毁失败");return 1;}printf("共享变量的值为: %d\n", shared_variable);return 0;
}
  1. 线程的同步 - 条件变量(Condition Variable)
    • 基本概念
      • 条件变量用于在线程之间进行同步,它允许一个线程等待某个条件为真。通常与互斥锁一起使用,一个线程可以在满足某个条件时通知其他等待该条件的线程。
    • 条件变量相关函数
      • pthread_cond_init函数:用于初始化一个条件变量。函数原型为int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);,其中cond是指向pthread_cond_t类型变量的指针,用于存储条件变量,attr是指向条件变量属性的指针,如果为NULL,则使用默认属性初始化。
      • pthread_cond_wait函数:用于让一个线程等待条件变量满足。函数原型为int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);,在调用该函数时,线程会释放已经获取的互斥锁mutex,然后进入等待状态,直到另一个线程通过pthread_cond_signal或者pthread_cond_broadcast函数唤醒它,并且在被唤醒后会重新获取互斥锁。
      • pthread_cond_signal函数:用于唤醒一个等待条件变量的线程。函数原型为int pthread_cond_signal(pthread_cond_t *cond);,它会唤醒至少一个等待条件变量cond的线程。
      • pthread_cond_broadcast函数:用于唤醒所有等待条件变量的线程。函数原型为int pthread_cond_broadcast(pthread_cond_t *cond);
      • pthread_cond_destroy函数:用于销毁条件变量。函数原型为int pthread_cond_destroy(pthread_cond_t *cond);,在条件变量不再使用时,应该销毁它,释放相关资源。
    • 示例代码(使用条件变量和互斥锁实现线程同步)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 定义互斥锁和条件变量
pthread_mutex_t mutex;
pthread_cond_t cond;
// 共享变量,表示资源是否可用
int resource_available = 0;
// 线程1执行的函数,用于生产资源
void *thread1_function(void *arg) {// 模拟生产资源的过程// 这里简单地等待一段时间后生产资源sleep(2);// 锁定互斥锁pthread_mutex_lock(&mutex);resource_available = 1;// 发送信号,通知等待资源的线程pthread_cond_signal(&cond);// 解锁互斥锁pthread_mutex_unlock(&mutex);return NULL;
}
// 线程2执行的函数,用于消费资源
void *thread2_function(void *arg) {// 锁定互斥锁pthread_mutex_lock(&mutex);// 检查资源是否可用,如果不可用则等待while (!resource_available) {pthread_cond_wait(&cond, &mutex);}// 消费资源,这里简单地打印一条消息printf("资源已被消费。\n");// 解锁互斥锁pthread_mutex_unlock(&mutex);return NULL;
}
int main() {pthread_t thread_id1, thread_id2;int result;// 初始化互斥锁和条件变量result = pthread_mutex_init(&mutex, NULL);if (result!= 0) {perror("互斥锁初始化失败");return 1;}result = pthread_cond_init(&cond, NULL);if (result!= 0) {perror("条件变量初始化失败");return 1;}// 创建两个线程result = pthread_create(&thread_id1, NULL, thread1_function, NULL);if (result!= 0) {perror("线程1创建失败");return 1;}result = pthread_create(&thread_id2, NULL, thread2_function, NULL);if (result!= 0) {perror("线程2创建失败");return 1;}// 等待线程结束result = pthread_join(thread_id1, NULL);if (result!= 0) {perror("等待线程1结束失败");return 1;}result = pthread_join(thread_id2, NULL);if (result!= 0) {perror("等待线程2结束失败");return 1;}// 销毁互斥锁和条件变量result = pthread_mutex_destroy(&mutex);if (result!= 0) {perror("互斥锁销毁失败");return 1;}result = pthread_cond_destroy(&cond);if (result!= 0) {perror("条件变量销毁失败");return 1;}return 0;
}

在这里插入图片描述

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

相关文章:

  • 【JavaEE初阶】线程 和 thread
  • 如何规避eBay账号被封的风险?原因与对策
  • Word使用分隔符实现页面部分分栏
  • Express (nodejs) 相关
  • 【Harmony Next】多个图文配合解释DevEco Studio工程中,如何配置App相关内容,一次解决多个问题?
  • 台球助教平台开发球厅预约选择机制和助教匹配选择机制详细需求实例说明(第十四章)
  • MyBatis通过注解配置执行SQL语句原理源码分析
  • 开放词汇目标检测(Open-Vocabulary Object Detection, OVOD)综述
  • PHP基础
  • 启用WSL后,使用ssh通道连接ubuntu
  • GMSSL的不同python版本
  • 【数理统计】参数估计
  • ios 混合开发应用白屏问题
  • 对分布式系统的理解以及redis的分布式实现
  • VS项目,在生成的时候自动修改版本号
  • 【蓝桥杯】43699-四平方和
  • 我的“双胞同体”发布模式的描述与展望
  • flask_socketio 以继承 Namespace方式实现一个网页聊天应用
  • go mod tidy 命令
  • (11)YOLOv9算法基本原理
  • python学opencv|读取图像(十七)认识alpha通道
  • 中小学教室多媒体电脑安全登录解决方案
  • Redis篇之Redis高可用模式参数调优,提高Redis性能
  • linux-----进程execl簇函数
  • Vue + ECharts 实现山东地图展示与交互
  • 【Verilog】UDP用户原语
  • 问题小记-达梦数据库报错“字符串转换出错”处理
  • MyBatis入门的详细应用实例
  • Sequelize ORM sql 语句工具
  • 增强LabVIEW与PLC通信稳定性