15-LINUX--线程的创建与同步

一.线程

1.线程的概念

    线程是进程内部的一条执行序列或执行路径,一个进程可以包含多条线程。

2.线程的三种实现方式

◼ 内核级线程:由内核创建,创建开销大,内核能感知到线程的存在
◼ 用户级线程:线程的创建有用户空间的线程库完成;内核不知道线程的存在
组合级线程:兼顾以上两者的优点,
区别:两个处理器,用户级线程在内核上无法并行处理,只能交替执行;内核级可以同时执行;组合技在不同的空间采用不同的处理方式

线程同步的方法:信号量,互斥锁,条件变量,读写锁

Ps -elf 查看线程ID

Linux 中线程的实现:

Linux 实现线程的机制非常独特。从内核的角度来说,它并没有线程这个概念。Linux 把
所有的线程都当做进程来实现。内核并没有准备特别的调度算法或是定义特别的数据结构来
表征线程。相反,线程仅仅被视为一个与其他进程共享某些资源的进程。每个线程都拥有唯
一隶属于自己的 task_struct,所以在内核中,它看起来就像是一个普通的进程(只是线程和
其他一些进程共享某些资源,如地址空间)。

3.进程与线程的区别

        ◼ 进程是资源分配的最小单位,线程是 CPU 调度的最小单位
        ◼ 进程有自己的独立地址空间,线程共享进程中的地址空间
        ◼ 进程的创建消耗资源大,线程的创建相对较小
        ◼ 进程的切换开销大,线程的切换开销相对较小

二.线程使用

1.线程库

 #include <pthread.h>/*pthread_create()用于创建线程thread: 接收创建的线程的 IDattr: 指定线程的属性start_routine: 指定线程函数arg: 给线程函数传递的参数成功返回 0, 失败返回错误码*/int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);13./*pthread_exit()退出线程retval:指定退出信息*/int pthread_exit(void *retval);/*pthread_join()等待 thread 指定的线程退出,线程未退出时,该方法阻塞retval:接收 thread 线程退出时,指定的退出信息
*/int pthread_join(pthread_t thread, void **retval);

多线程代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <pthread.h>void * pthread_fun(void *arg){int i = 0;for(; i < 5; ++i){sleep(1);printf("fun thread running\n");}pthread_exit("fun over");}int main(){pthread_t tid;int res = pthread_create(&tid, NULL, pthread_fun, NULL);assert(res == 0);int i = 0;for(; i < 5; ++i){sleep(1);printf("main thread running\n");}char *s = NULL;pthread_join(tid, (void **)&s);printf("s = %s\n", s);exit(0);}

三.线程同步

       线程同步指的是当一个线程在对某个临界资源进行操作时,其他线程都不可以对这个资
源进行操作,直到该线程完成操作,其他线程才能操作,也就是协同步调,让线程按预定的
先后次序进行运行。 线程同步的方法有四种:互斥锁、信号量、条件变量、读写锁。

1.互斥锁

#include <pthread.h>int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr);//初始化锁int pthread_mutex_lock(pthread_mutex_t *mutex);//上锁,其他线程无法使用int pthread_mutex_unlock(pthread_mutex_t *mutex);//开锁int pthread_mutex_destroy(pthread_mutex_t *mutex);//销毁锁
为什么线程需要同步和互斥的操作?
因为线程引入共享了进程的地址空间,导致了一个线程操作数据时候,极其容易影响到其他线程的情况;对其他线程造成不可控因素,或引起异常,逻辑结果不正确的情况;这也是线程不安全的原因!
重点概念:
        示例代码如下,主线程和函数线程模拟访问打印机,主线程输出第一个字符‘a’表示开
始使用打印机,输出第二个字符‘a’表示结束使用,函数线程操作与主线程相同。(由于打
印机同一时刻只能被一个线程使用,所以输出结果不应该出现 abab)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>//sem_t sem;
pthread_mutex_t mutex;
void* fun1(void* arg)
{for(int i=0;i<5;i++){//sem_wait(&sem);pthread_mutex_lock(&mutex);printf("A");fflush(stdout);int n=rand()%3;sleep(n);printf("A");fflush(stdout);//sem_post(&sem);pthread_mutex_unlock(&mutex);n=rand()%3;sleep(n);}
}
void* fun2(void* arg)
{for(int i=0;i<5;i++){//sem_wait(&sem);pthread_mutex_lock(&mutex);printf("B");fflush(stdout);int n=rand()%3;sleep(n);printf("B");fflush(stdout);//sem_post(&sem);pthread_mutex_unlock(&mutex);n=rand()%3;sleep(n);}}
int main()
{//sem_init(&sem,0,1);pthread_mutex_init(&mutex,NULL);pthread_t id1,id2;pthread_create(&id1,NULL,fun1,NULL);pthread_create(&id2,NULL,fun2,NULL);pthread_join(id1,NULL);pthread_join(id2,NULL);//sem_destroy(&sem);pthread_mutex_destroy(&mutex);exit(0);
}

2.信号量

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>char buff[128] = {0};sem_t sem1;sem_t sem2;void* PthreadFun(void *arg)
{int fd = open("a.txt", O_RDWR | O_CREAT, 0664);assert(fd != -1);//函数线程完成将用户输入的数据存储到文件中while(1){sem_wait(&sem2);if(strncmp(buff, "end", 3) == 0){break;}write(fd, buff, strlen(buff));memset(buff, 0, 128);sem_post(&sem1);}sem_destroy(&sem1);sem_destroy(&sem2);}int main(){sem_init(&sem1, 0, 1);sem_init(&sem2, 0, 0);pthread_t id;int res = pthread_create(&id, NULL, PthreadFun, NULL);assert(res == 0);//主线程完成获取用户数据的数据,并存储在全局数组 buff 中while(1){sem_wait(&sem1);printf("please input data: ");fflush(stdout);fgets(buff, 128, stdin);buff[strlen(buff) - 1] = 0;sem_post(&sem2);if(strncmp(buff, "end", 3) == 0){break;}}pthread_exit(NULL);}

3.条件变量

条件变量是利用线程间共享的全局变量进行同步的一种机制。
主要包括两个动作:一个线程等待”条件变量的条件成立”而挂起;另一个线程使”条件成立”(给出条件成立信号)。
为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。
条件变量类型为 pthread_cond_t。

条件变量接口

pthread_cond_init()       //初始化
pthread_cond_wait()       //等待将信息存入并等待达到唤醒条件
pthread_cond_signal()     //只唤醒一个
pthread_cond_broadcast()  //唤醒所以有的线程
条件变量有什么用

使用条件变量可以以原子方式阻塞线程,直到某个特定条件为真为止。条件变量始终与互斥锁一起使用,对条件的测试是在互斥锁(互斥)的保护下进行的

如果条件为假,线程通常会基于条件变量阻塞,并以原子方式释放等待条件变化的互斥锁。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>pthread_cond_t cond;
pthread_mutex_t mutex;
void* funa(void* arg)
{char* s =(char*)arg;while(1){pthread_mutex_lock(&mutex);pthread_cond_wait(&cond,&mutex);//添加到条件变量的等待队列,阻塞pthread_mutex_unlock(&mutex);if(strncmp(s,"end",3)==0){break;}printf("funa:%s\n",s);}
}
void* funb(void* arg)
{char* s =(char*)arg;while(1){pthread_mutex_lock(&mutex);pthread_cond_wait(&cond,&mutex);//添加到条件变量的等待队列,阻塞pthread_mutex_unlock(&mutex);if(strncmp(s,"end",3)==0){break;}printf("funb:%s\n",s);}}
int main()
{pthread_mutex_init(&mutex,NULL);pthread_cond_init(&cond,NULL);pthread_t id1,id2;char buff[128]={0};pthread_create(&id1,NULL,funa,buff);pthread_create(&id2,NULL,funb,buff);while(1){char tmp[128]={0};fgets(tmp,128,stdin);strcpy(buff,tmp);if(strncmp(tmp,"end",3)==0){pthread_mutex_lock(&mutex);pthread_cond_broadcast(&cond);//唤醒所有线程pthread_mutex_unlock(&mutex);break;}else{pthread_mutex_lock(&mutex);pthread_cond_signal(&cond);//唤醒一个pthread_mutex_unlock(&mutex);}}pthread_join(id1,NULL);pthread_join(id2,NULL);pthread_mutex_destroy(&mutex);pthread_cond_destroy(&cond);exit(0);
}

4.读写锁

读写锁:是一对锁,分为读锁和写锁,允许多个线程同时获取读写锁,但再通过一时间,只允许一个线程获得写锁,或者可以由多个线程获得读锁

接口:

#include <pthread.h>int pthread_rwlock_init(pthread_rwlock_t *rwlock, pthread_rwlockattr_t *attr);int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

代码示例

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>pthread_rwlock_t lock;void* fun_r1(void* arg)
{for(int i=0;i<10;i++){pthread_rwlock_rdlock(&lock);printf("fun r1 start\n");int n=rand()%3;sleep(n);printf("fun r1 end\n");pthread_rwlock_unlock(&lock);n=rand()%3;sleep(n);}
}void* fun_r2(void* arg)
{for(int i=0;i<10;i++){pthread_rwlock_rdlock(&lock);printf("fun r2 start\n");int n=rand()%3;sleep(n);printf("fun r2 end\n");pthread_rwlock_unlock(&lock);n=rand()%3;sleep(n);}}void* fun_w(void* arg)
{for(int i=0;i<10;i++){pthread_rwlock_wrlock(&lock);printf(" fun w start\n");int n=rand()%3;sleep(n);printf(" fun w end\n");pthread_rwlock_wrlock(&lock);n = rand()%3;sleep(n);}
}int main()
{pthread_rwlock_init(&lock,NULL);pthread_t id1,id2,id3;pthread_create(&id1,NULL,fun_r1,NULL);pthread_create(&id2,NULL,fun_r2,NULL);pthread_create(&id3,NULL,fun_w,NULL);pthread_join(id1,NULL);pthread_join(id2,NULL);pthread_join(id3,NULL);pthread_rwlock_destroy(&lock);exit(0);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/9287.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

刷题第3天(简单题):LeetCode206--反转链表--双指针法

LeetCode206&#xff1a;给你单链表的头节点 head &#xff0c;请你反转链表&#xff0c;并返回反转后的链表。 示例 1&#xff1a; 输入&#xff1a;head [1,2,3,4,5] 输出&#xff1a;[5,4,3,2,1]示例 2&#xff1a; 输入&#xff1a;head [1,2] 输出&#xff1a;[2,1]示例…

五一超级课堂---Llama3-Tutorial(Llama 3 超级课堂)---第三节llama 3图片理解能力微调(xtuner+llava版)

课程文档&#xff1a; https://github.com/SmartFlowAI/Llama3-Tutorial 课程视频&#xff1a; https://space.bilibili.com/3546636263360696/channel/collectiondetail?sid2892740&spm_id_from333.788.0.0 操作平台&#xff1a; https://studio.intern-ai.org.cn/consol…

【Web前端】jquery_json

1.jquery 1.1jquery简介 jquery是一个快速、简洁的javascript框架&#xff0c;于2006年1月份发布。jquery设计的宗旨是"write less,domore"&#xff0c;倡导写更少的代码&#xff0c;做更多的事情。封装了javascript常用的一些功能代码&#xff0c;提供一种简便的j…

postman---认证(Certificates)是什么作用?

在 Postman 中&#xff0c;认证&#xff08;Certificates&#xff09;功能主要用于处理 TLS 客户端认证。TLS&#xff08;传输层安全性&#xff09;是用于保护网络通信安全的协议&#xff0c;它使用数字证书来验证通信双方的身份。在 Postman 中&#xff0c;认证功能允许您上传…

自动镭雕机价格是多少?

自动镭雕机是一种高精度、高效率的激光雕刻设备&#xff0c;广泛应用于手机、电脑、玻璃等产品表面的图案雕刻。那么&#xff0c;自动镭雕机多少钱一台呢&#xff1f;本文将为您详细解析各种因素对自动镭雕机价格的影响。 一、影响自动镭雕机价格的因素 1. 品牌和质量 自动镭…

itext7 PDF添加水印,获取页面高度,添加到页面右上角

ps: pdf添加水印&#xff0c;内容多的时候会往下跑&#xff0c;修改为获取当前页面高度&#xff0c;进行固定在顶部&#xff0c;其他需要可以自己进行调整&#xff0c;直接贴代码。 public static void main(String[] args) throws IOException {String localFilePath "…

xiuno(修罗)知乎模板二开优化魔板仿网盘资源社–模板加全套插件

使用说明 以服务器为例搭建教程 ①先安装 PHP7.1 版本 再安装数据库 Mysql ②解压文件&#xff1a;xiunobbs_4.0.4&#xff08;解压到根目录&#xff09;.zip ③解压②完成后找到【plugin】文件夹再解压&#xff1a;plugin(解压到 plugin 文件夹).zip 设置伪静态代码在上面&am…

知从科技应邀参加恩智浦技术日巡回研讨会郑州站汽车电子专场

4月18日&#xff0c;恩智浦技术日巡回研讨会的首个汽车电子专场在郑州成功举办。此次研讨会汇聚了众多行业专家&#xff0c;聚焦前沿的赋能技术&#xff0c;共同探讨汽车电子架构、ADAS、汽车电气化、车载信息娱乐系统、UWB超宽带等热门应用。作为恩智浦合作伙伴&#xff0c;知…

【python量化交易】qteasy使用教程05——创建第一个自定义交易策略

创建第一个自定义交易策略 使用qteasy创建自定义交易策略开始前的准备工作本节的目标自定义策略的实现方法使用 qteasy 的 Strategy 策略类三种不同的自定义策略基类定义一个双均线择时交易策略定义策略运行时机定义策略需要的数据自定义交易策略的实现&#xff1a;realize()获…

Gitee 码云与Git 交互

优质博文&#xff1a;IT-BLOG-CN 一、进入码云官方网站&#xff0c;注册用户 码云(Gitee.com)是一个类似于GitHub的在线代码托管平台。 码云提供了包括版本控制、代码托管、协作开发和代码分享等功能&#xff0c;基于Git开发&#xff0c;支持代码在线查看、历史版本查看、Fo…

回归的无分布预测推理

摘要 我们利用保形推理&#xff0c;开发了回归中无分布预测推理的一般框架。所提出的方法允许使用回归函数的任何估计量构建响应变量的预测带。所得的预测带在标准假设下保留了原始估计量的一致性&#xff0c;同时保证了有限样本边际覆盖&#xff0c;即使这些假设不成立。我们…

echarts-gl 离线3D地图

1、安装依赖 echarts-gl 与 echarts 版本关系&#xff1a; "echarts": "^5.2.0", "echarts-gl": "^2.0.8"# 执行安装 yarn add echarts-gl2、下载离线地图 免费下载实时更新的geoJson数据、行政区划边界数据、区划边界坐标集合_…

容器化Jenkins远程发布java应用(方式二:自定义镜像仓库远程拉取构建)

1.创建maven项目 2.配置git、maven 3.阿里控制台>容器镜像服务>镜像仓库>创建镜像仓库 4.执行shell脚本&#xff08;推送镜像到阿里云镜像仓库&#xff09; 使用到登录阿里云仓库命令 #!/bin/bash # 服务名称 SERVER_NAMEplanetflix-app # 镜像tag IMAGE_TAG1.0.0-SN…

亚马逊云科技中国峰会:与你开启云计算与前沿技术的探索之旅

亚马逊云科技中国峰会&#xff1a;与你开启云计算与前沿技术的探索之旅 Hello,我是科技博主Maynor&#xff0c;非常高兴地向你们推荐亚马逊云科技中国峰会&#xff0c;这是一场将于 5 月 29 日至 30 日在上海世博中心举办的科技盛会&#xff0c;如果你对云计算、行业发展新趋势…

计算机网络教材——谢希仁教材与配套PPT课件和《计算机网络——自顶向下方法》

教材链接: https://pan.baidu.com/s/1MUkgTVNMvhFdkGxAd0U7Ew?pwdn3g4 提取码: n3g4 ppt资源&#xff1a;课程包列表 (51zhy.cn) 计算机网络——自顶向下方法&#xff08;资源在下面的评论区里&#xff09;&#xff1a;计算机网络自顶向下方法第7版中文PDF习题参考 - 哔哩哔…

Android Studio高版本安卓模拟器抓取https包

Android Studio avd 设置 证书生成 *.cer格式证书​ openssl x509 -inform DER -subject\_hash\_old -in charles-ssl-proxying-certificate.cer​ *.pem格式证书​ openssl x509 -inform PEM -subject\_hash\_old -in charles-ssl-proxying-certificate.pem会输出 2cb30a9e …

使用Python实现循环神经网络(RNN)的博客教程

循环神经网络&#xff08;Recurrent Neural Network&#xff0c;RNN&#xff09;是一种能够处理序列数据的神经网络模型&#xff0c;常用于自然语言处理、时间序列分析等任务。本教程将介绍如何使用Python和PyTorch库实现一个简单的循环神经网络&#xff0c;并演示如何在一个简…

java 中文繁简体转换工具 opencc4j

目录 一、简介 二、使用案例 繁简体转换 转为简体 toSimple 转为繁体 toTraditional 繁简体判断 是否为简体 isSimple 三、优缺点 优点 一、简介 OpenCC4J 是 OpenCC 的 Java 版本&#xff0c;OpenCC 是一个开源的简体字到繁体字转换工具&#xff0c;它支持多种转换配…

kafka系列三:生产与消费实践之旅

在本篇技术博客中&#xff0c;我们将深入探索Apache Kafka 0.10.0.2版本中的消息生产与消费机制。Kafka作为一个分布式消息队列系统&#xff0c;以其高效的吞吐量、低延迟和高可扩展性&#xff0c;在大数据处理和实时数据流处理领域扮演着至关重要的角色。了解如何在这一特定版…

Java 高级面试问题及答案 更新(二)

Java 高级面试问题及答案 以下是几个常见的Java高级面试问题及其答案&#xff0c;供参考。 1. 什么是Java内存模型&#xff08;JMM&#xff09;&#xff1f;它如何影响并发编程&#xff1f; 问题&#xff1a;在Java中&#xff0c;内存模型&#xff08;JMM&#xff09;是一个…