Linux 线程同步的三种方法

2023-11-02

线程的最大特点是资源的共享性,但资源共享中的同步问题是多线程编程的难点。linux下提供了多种方式来处理线程同步,最常用的是互斥锁、条件变量和信号量。

一、互斥锁(mutex)

通过锁机制实现线程间的同步。

  1. 初始化锁。在Linux下,线程的互斥量数据类型是pthread_mutex_t。在使用前,要对它进行初始化。
    静态分配:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    动态分配:int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex_attr_t *mutexattr);
  2. 加锁。对共享资源的访问,要对互斥量进行加锁,如果互斥量已经上了锁,调用线程会阻塞,直到互斥量被解锁。
    int pthread_mutex_lock(pthread_mutex *mutex);
    int pthread_mutex_trylock(pthread_mutex_t *mutex);
  3. 解锁。在完成了对共享资源的访问后,要对互斥量进行解锁。
    int pthread_mutex_unlock(pthread_mutex_t *mutex);
  4. 销毁锁。锁在是使用完成后,需要进行销毁以释放资源。
    int pthread_mutex_destroy(pthread_mutex *mutex);
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <pthread.h>
#include "iostream"
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int tmp;
void* thread(void *arg)
{
	cout << "thread id is " << pthread_self() << endl;
	pthread_mutex_lock(&mutex);
	tmp = 12;
	cout << "Now a is " << tmp << endl;
	pthread_mutex_unlock(&mutex);
	return NULL;
}
int main()
{
	pthread_t id;
	cout << "main thread id is " << pthread_self() << endl;
	tmp = 3;
	cout << "In main func tmp = " << tmp << endl;
	if (!pthread_create(&id, NULL, thread, NULL))
	{
		cout << "Create thread success!" << endl;
	}
	else
	{
		cout << "Create thread failed!" << endl;
	}
	pthread_join(id, NULL);
	pthread_mutex_destroy(&mutex);
	return 0;
}
//编译:g++ -o thread testthread.cpp -lpthread

二、条件变量(cond)

互斥锁不同,条件变量是用来等待而不是用来上锁的。条件变量用来自动阻塞一个线程,直到某特殊情况发生为止。通常条件变量和互斥锁同时使用。条件变量分为两部分: 条件和变量。条件本身是由互斥量保护的。线程在改变条件状态前先要锁住互斥量。条件变量使我们可以睡眠等待某种条件出现。条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起;另一个线程使"条件成立"(给出条件成立信号)。条件的检测是在互斥锁的保护下进行的。如果一个条件为假,一个线程自动阻塞,并释放等待状态改变的互斥锁。如果另一个线程改变了条件,它发信号给关联的条件变量,唤醒一个或多个等待它的线程,重新获得互斥锁,重新评价条件。如果两进程共享可读写的内存,条件变量可以被用来实现这两进程间的线程同步。

  1. 初始化条件变量。
    静态态初始化,pthread_cond_t cond = PTHREAD_COND_INITIALIER;
    动态初始化,int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);
  2. 等待条件成立。释放锁,同时阻塞等待条件变量为真才行。timewait()设置等待时间,仍未signal,返回ETIMEOUT(加锁保证只有一个线程wait)
    int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
    int pthread_cond_timewait(pthread_cond_t *cond,pthread_mutex *mutex,const timespec *abstime);
  3. 激活条件变量。pthread_cond_signal,pthread_cond_broadcast(激活所有等待线程)
    int pthread_cond_signal(pthread_cond_t *cond);
    int pthread_cond_broadcast(pthread_cond_t *cond); //解除所有线程的阻塞
  4. 清除条件变量。无线程等待,否则返回EBUSY
    int pthread_cond_destroy(pthread_cond_t *cond);
#include <stdio.h>
#include <pthread.h>
#include "stdlib.h"
#include "unistd.h"
pthread_mutex_t mutex;
pthread_cond_t cond;
void hander(void *arg)
{
	free(arg);
	(void)pthread_mutex_unlock(&mutex);
}
void *thread1(void *arg)
{
	pthread_cleanup_push(hander, &mutex);
	while(1)
	{
		printf("thread1 is running\n");
		pthread_mutex_lock(&mutex);
		pthread_cond_wait(&cond, &mutex);
		printf("thread1 applied the condition\n");
		pthread_mutex_unlock(&mutex);
		sleep(4);
	}
	pthread_cleanup_pop(0);
}
void *thread2(void *arg)
{
	while(1)
	{
		printf("thread2 is running\n");
		pthread_mutex_lock(&mutex);
		pthread_cond_wait(&cond, &mutex);
		printf("thread2 applied the condition\n");
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
}
int main()
{
	pthread_t thid1,thid2;
	printf("condition variable study!\n");
	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);
	pthread_create(&thid1, NULL, thread1, NULL);
	pthread_create(&thid2, NULL, thread2, NULL);
	sleep(1);
	do
	{
		pthread_cond_signal(&cond);
	}while(1);
	sleep(20);
	pthread_exit(0);
	return 0;
}
#include <pthread.h>
#include <unistd.h>
#include "stdio.h"
#include "stdlib.h"
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node
{
	int n_number;
	struct node *n_next;
}*head = NULL;

static void cleanup_handler(void *arg)
{
	printf("Cleanup handler of second thread./n");
	free(arg);
	(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
	struct node *p = NULL;
	pthread_cleanup_push(cleanup_handler, p);
	while (1)
	{
		//这个mutex主要是用来保证pthread_cond_wait的并发性
		pthread_mutex_lock(&mtx);
		while (head == NULL)
		{
			//这个while要特别说明一下,单个pthread_cond_wait功能很完善,为何
			//这里要有一个while (head == NULL)呢?因为pthread_cond_wait里的线
			//程可能会被意外唤醒,如果这个时候head != NULL,则不是我们想要的情况。
			//这个时候,应该让线程继续进入pthread_cond_wait
			// pthread_cond_wait会先解除之前的pthread_mutex_lock锁定的mtx,
			//然后阻塞在等待对列里休眠,直到再次被唤醒(大多数情况下是等待的条件成立
			//而被唤醒,唤醒后,该进程会先锁定先pthread_mutex_lock(&mtx);,再读取资源
			//用这个流程是比较清楚的
			pthread_cond_wait(&cond, &mtx);
			p = head;
			head = head->n_next;
			printf("Got %d from front of queue/n", p->n_number);
			free(p);
		}
		pthread_mutex_unlock(&mtx); //临界区数据操作完毕,释放互斥锁
	}
	pthread_cleanup_pop(0);
	return 0;
}
int main(void)
{
	pthread_t tid;
	int i;
	struct node *p;
	//子线程会一直等待资源,类似生产者和消费者,但是这里的消费者可以是多个消费者,而
	//不仅仅支持普通的单个消费者,这个模型虽然简单,但是很强大
	pthread_create(&tid, NULL, thread_func, NULL);
	sleep(1);
	for (i = 0; i < 10; i++)
	{
		p = (struct node*)malloc(sizeof(struct node));
		p->n_number = i;
		pthread_mutex_lock(&mtx); //需要操作head这个临界资源,先加锁,
		p->n_next = head;
		head = p;
		pthread_cond_signal(&cond);
		pthread_mutex_unlock(&mtx); //解锁
		sleep(1);
	}
	printf("thread 1 wanna end the line.So cancel thread 2./n");
	//关于pthread_cancel,有一点额外的说明,它是从外部终止子线程,子线程会在最近的取消点,退出
	//线程,而在我们的代码里,最近的取消点肯定就是pthread_cond_wait()了。
	pthread_cancel(tid);
	pthread_join(tid, NULL);
	printf("All done -- exiting/n");
	return 0;
}

三、信号量(sem)

如同进程一样,线程也可以通过信号量来实现通信,虽然是轻量级的。信号量函数的名字都以"sem_"打头。线程使用的基本信号量函数有四个。

  1. 信号量初始化。
    int sem_init (sem_t *sem , int pshared, unsigned int value);
    这是对由sem指定的信号量进行初始化,设置好它的共享选项(linux 只支持为0,即表示它是当前进程的局部信号量),然后给它一个初始值VALUE。
  2. 等待信号量。给信号量减1,然后等待直到信号量的值大于0。
    int sem_wait(sem_t *sem);
  3. 释放信号量。信号量值加1。并通知其他等待线程。
    int sem_post(sem_t *sem);
  4. 销毁信号量。我们用完信号量后都它进行清理。归还占有的一切资源。
    int sem_destroy(sem_t *sem);
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
#define return_if_fail(p) if((p) == 0){printf ("[%s]:func error!/n", __func__);return;}
typedef struct _PrivInfo
{
	sem_t s1;
	sem_t s2;
	time_t end_time;
}PrivInfo;

static void info_init (PrivInfo* thiz);
static void info_destroy (PrivInfo* thiz);
static void* pthread_func_1 (PrivInfo* thiz);
static void* pthread_func_2 (PrivInfo* thiz);

int main (int argc, char** argv)
{
	pthread_t pt_1 = 0;
	pthread_t pt_2 = 0;
	int ret = 0;
	PrivInfo* thiz = NULL;
	thiz = (PrivInfo* )malloc (sizeof (PrivInfo));
	if (thiz == NULL)
	{
		printf ("[%s]: Failed to malloc priv./n");
		return -1;
	}
	info_init (thiz);
	ret = pthread_create (&pt_1, NULL, (void*)pthread_func_1, thiz);
	if (ret != 0)
	{
		perror ("pthread_1_create:");
	}
	ret = pthread_create (&pt_2, NULL, (void*)pthread_func_2, thiz);
	if (ret != 0)
	{
		perror ("pthread_2_create:");
	}
	pthread_join (pt_1, NULL);
	pthread_join (pt_2, NULL);
	info_destroy (thiz);
	return 0;
}
static void info_init (PrivInfo* thiz)
{
	return_if_fail (thiz != NULL);
	thiz->end_time = time(NULL) + 10;
	sem_init (&thiz->s1, 0, 1);
	sem_init (&thiz->s2, 0, 0);
	return;
}
static void info_destroy (PrivInfo* thiz)
{
	return_if_fail (thiz != NULL);
	sem_destroy (&thiz->s1);
	sem_destroy (&thiz->s2);
	free (thiz);
	thiz = NULL;
	return;
}
static void* pthread_func_1 (PrivInfo* thiz)
{
	return_if_fail(thiz != NULL);
	while (time(NULL) < thiz->end_time)
	{
		sem_wait (&thiz->s2);
		printf ("pthread1: pthread1 get the lock./n");
		sem_post (&thiz->s1);
		printf ("pthread1: pthread1 unlock/n");
		sleep (1);
	}
	return;
}
static void* pthread_func_2 (PrivInfo* thiz)
{
	return_if_fail (thiz != NULL);
	while (time (NULL) < thiz->end_time)
	{
		sem_wait (&thiz->s1);
		printf ("pthread2: pthread2 get the unlock./n");
		sem_post (&thiz->s2);
		printf ("pthread2: pthread2 unlock./n");
		sleep (1);
	}
	return;
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Linux 线程同步的三种方法 的相关文章

  • 如何使用 sed 仅删除双空行?

    我找到了这个问题和答案 https stackoverflow com questions 4651591 howto use sed to remove only triple empty lines关于如何删除三重空行 但是 我只需要对
  • SONAR - 使用 Cobertura 测量代码覆盖率

    我正在使用声纳来测量代码质量 我不知道的一件事是使用 Cobertura 测量代码覆盖率的步骤 我按照以下步骤操作http cobertura sourceforge net anttaskreference html http cober
  • 如何制作和应用SVN补丁?

    我想制作一个SVN类型的补丁文件httpd conf这样我就可以轻松地将其应用到其他主机上 If I do cd root diff Naur etc httpd conf httpd conf original etc httpd con
  • 并行运行 make 时出错

    考虑以下制作 all a b a echo a exit 1 b echo b start sleep 1 echo b end 当运行它时make j2我收到以下输出 echo a echo b start a exit 1 b star
  • QFileDialog::getSaveFileName 和默认的 selectedFilter

    我有 getSaveFileName 和一些过滤器 我希望当用户打开 保存 对话框时选择其中之一 Qt 文档说明如下 可以通过将 selectedFilter 设置为所需的值来选择默认过滤器 我尝试以下变体 QString selFilte
  • ansible 重新启动 2.1.1.0 失败

    我一直在尝试创建一个非常简单的 Ansible 剧本 它将重新启动服务器并等待它回来 我过去在 Ansible 1 9 上有一个可以运行的 但我最近升级到 2 1 1 0 并且失败了 我正在重新启动的主机名为 idm IP 为 192 16
  • Locale.getDefault() 始终返回 en

    unix 机器上的服务器始终使用 en 作为默认区域设置 以下是区域设置输出 LANG en US LC CTYPE C LC NUMERIC C LC TIME C LC COLLATE C LC MONETARY C LC MESSAG
  • 拆分字符串以仅获取前 5 个字符

    我想去那个地点 var log src ap kernelmodule 10 001 100 但看起来我的代码必须处理 ap kernelmodule 10 002 100 ap kernelmodule 10 003 101 等 我想使用
  • 修改linux下的路径

    虽然我认为我已经接近 Linux 专业人士 但显然我仍然是一个初学者 当我登录服务器时 我需要使用最新版本的R 统计软件 R 安装在 2 个地方 当我运行以下命令时 which R I get usr bin R 进而 R version
  • bluetoothctl 到 hcitool 等效命令

    在 Linux 中 我曾经使用 hidd connect mmac 来连接 BT 设备 但自 Bluez5 以来 这种情况已经消失了 我可以使用 bluetoothctl 手动建立连接 但我需要从我的应用程序使用这些命令 并且使用 blue
  • 应用程序无缘无故地被杀死。怀疑 BSS 高。如何调试呢?

    我已经在CentOs6 6中成功运行我的应用程序 最近 硬件 主板和内存 更新了 我的应用程序现在毫无理由地被杀死 root localhost PktBlaster PktBlaster Killed 文件和 ldd 输出 root lo
  • 无法在 JavaScript for 循环中读取 null 的属性“长度”

    我正在尝试制作一个像 Stack Overflow 那样的 Markdown 编辑器 如果我实际上没有在文本区域中键入星号和包含短语的 http 我会收到标题中列出的此错误 如果我只输入包含星号的短语 则错误指的是这一行 if linkif
  • Jenkins中找不到环境变量

    我想在詹金斯中设置很多变量 我试过把它们放进去 bashrc bash profile and profile of the jenkins用户 但 Jenkins 在构建发生时找不到它们 唯一有效的方法是将所有环境变量放入Jenkinsf
  • 如何在 shell 脚本中并行运行多个实例以提高时间效率[重复]

    这个问题在这里已经有答案了 我正在使用 shell 脚本 它读取 16000 行的输入文件 运行该脚本需要8个多小时 我需要减少它 所以我将其划分为 8 个实例并读取数据 其中我使用 for 循环迭代 8 个文件 并在其中使用 while
  • sendfile64 只复制约2GB

    我需要使用 sendfile64 复制大约 16GB 的文件 到目前为止我所取得的成就是 include
  • Android 时钟滴答数 [赫兹]

    关于 proc pid stat 中应用程序的总 CPU 使用率 https stackoverflow com questions 16726779 total cpu usage of an application from proc
  • linux perf:如何解释和查找热点

    我尝试了linux perf https perf wiki kernel org index php Main Page今天很实用 但在解释其结果时遇到了困难 我习惯了 valgrind 的 callgrind 这当然是与基于采样的 pe
  • 添加要在给定命令中运行的 .env 变量

    我有一个 env 文件 其中包含如下变量 HELLO world SOMETHING nothing 前几天我发现了这个很棒的脚本 它将这些变量放入当前会话中 所以当我运行这样的东西时 cat env grep v xargs node t
  • arm64和armhf有什么区别?

    Raspberry Pi Type 3 具有 64 位 CPU 但其架构不是arm64 but armhf 有什么区别arm64 and armhf armhf代表 arm hard float 是给定的名称Debian 端口 https
  • 如何在 Linux shell 中将十六进制转换为 ASCII 字符?

    假设我有一个字符串5a 这是 ASCII 字母的十六进制表示Z 我需要找到一个 Linux shell 命令 它将接受一个十六进制字符串并输出该十六进制字符串代表的 ASCII 字符 所以如果我这样做 echo 5a command im

随机推荐

  • 【转】Web网站通知系统设计

    写在前面 通知系统是网站信息传播机制的重要的一部分 足够写一大章来说明 本文只梳理设计原则 后续相关内容会持续更新 这里的通知包括但不限于公告 提醒或消息 不同使用场景下的功能定义不同 关于各客户端平台 ios android wp等 的通
  • ST-LINK USB communication error 非常有效的解决方法

    引言 我们在用ST Link下载程序的时候 经常会遇到ST LINK USB communication error的问题 其实解决方法很简单 更新一下固件库就行 如下图所示 首先检查确定是ST LINK USB communication
  • Android Preference隐藏,删除方式

    在Android系统开发中 经常需要去掉或者隐藏原生设置的一些条目 一 隐藏 Preference 方法 VisibleForTesting static final String ENABLE enable Preference enab
  • 用老版的python和pycharm好,还是新版的python和pycharm好?

    千万不要贪图新酷去下载和安装python和pycharm最新版 因为亲身经历 老版稳定 新版容易出问题 python用3 6 3 9的最好 pycharm用2021年的最好
  • Qt平台下C++内存管理

    分享我在编程中的设计观念 遇到的技术点 让我们在工作和生活中一起追求自由 这几年 自由的概念让我印象深刻 前不久看到一个词叫辞职自由 对 我刚刚辞职 站在新公司小山丘前 我想别人在实现财务自由的时候 我在追求加班自由 加班时努力搬砖 同时也
  • SpringBoot +Thymeleaf 提交字符串日期类型 提示Failed to convert property value of type ‘java.lang.String‘

    SpringBoot Thymeleaf 员工新增页面提交字符串日期类型 后台提示 Failed to convert property value of type java lang String to required type jav
  • nuxtjs2.x配置tailwindcss

    背景 现在tailwindcss比较火 就想着在项目中配置一下 毕竟能节省好多自己写css的时间 tailwindcss中是有nuxt中配置tailwindcss的教程的 跟着做了一下 但是由于自己还是nuxt2 x 而官网教程是针对nux
  • Flask中请求数据的获取和返回响应

    一 表单数据的获取 ussername request form get uname 定义一个变量接收数据 从request form也就是请求表单中获取 二 flask文件的上传 先来了解flask中文件对象的属性 files 文件数据
  • 动手学深度学习——矩阵求导之自动求导

    深度学习框架通过自动计算导数 即自动微分 automatic differentiation 来加快求导 实际中 根据我们设计的模型 系统会构建一个计算图 computational graph 来跟踪计算是哪些数据通过哪些操作组合起来产生
  • 【C++】超详细入门——详解函数返回类型

    目录 无返回值的函数 有返回值的函数 如何返回值 不要返回局部变量或临时量的引用或指针 使用尾置返回类型或decltype 作者简介 即将大四的北京某能源高校学生 座右铭 九层之台 起于垒土 所以学习技术须脚踏实地 这里推荐一款刷题 模拟面
  • YOLOV5通道剪枝【附代码】

    之前的博客中已经实现了YOLOv4 YOLOR YOLOX的剪枝 经过了几天的辛勤努力 终于实现了YOLOv5的剪枝 相关链接如下 YOLOv4剪枝 剪枝相关细节理论这里有写 YOLOv4剪枝 YOLOX剪枝 YOLOX剪枝 YOLOR剪枝
  • GAN实现MNIST

    GAN是生成对抗网络 具体的原理这里就不详解了 该博文简要实现了GAN的搭建 在MNIST数据集上使用 亲测100 可用 导入相应的代码库 import tensorflow as tf import numpy as np import
  • ubuntu系统将磁盘剩余容量扩到文件目录上

    操作系统ubuntu 20 04 6 live server amd64 磁盘现状 lsblk 查看磁盘信息 df h 显示存在的卷组信息 Free PE 还有58G 开始扩容 1 调整命令 参考 1 例如增大至220G lvextend
  • 【华为OD机试2023】找等值元素 C++ Java Python

    华为OD机试2023 找等值元素 C Java Python 前言 如果您在准备华为的面试 期间有想了解的可以私信我 我会尽可能帮您解答 也可以给您一些建议 本文解法非最优解 即非性能最优 不能保证通过率 Tips1 机试为ACM 模式 你
  • 第十二届蓝桥杯国赛

    刚进行完第十二届蓝桥杯国赛 说一下题目感想 这次是四道填空题 六道代码题 感觉这次出的题还比较对路 不像原来很难做出来 但是也有粗心做错的题 算法前面考的到不多 后面大题考的多 动态规划 深搜等 过几天出成绩 希望成绩可以稍微喜人点 第一题
  • Unity UI -- (5)增加基础按钮功能

    分析分析一些常见UI 良好的UI设计会清晰地和用户沟通 用户知道他们能和屏幕上哪些东西交互 哪些不能 如果他们进行了交互 他们也要清楚地知道交互是否成功 换句话说 UI要提供给用户很多反馈 我们可以来看看在Unity里或者在计算机上的任何应
  • “Error running ‘Tomcat 9.0‘: Address localhost:1099 is already in use”报错问题

    Error running Tomcat 9 0 Address localhost 1099 is already in use 报错问题 使用idea运行tomcat时左下方出现红色小方块提示问题 Error running Tomca
  • 系统测试设计的10种方法

    一 等价类划分 等价类的概念 等价类 某个输入域的子集合 在这个集合中 每一个输入条件都是等效 的 如果其中一个输入不能导致问题发生 那么集合中其它输入条件进行测试也不可能发现错误 有效等价类 合理的输入数据 指满足产品规格说明的输入数据
  • swagger接口需要权限验证解决方案

    目录 背景 解决方案 背景 当我们在使用s w a g g e r的情况下 经常会遇到需要授权或者请求带有token才可以访问接口 这里我们就是解决授权问题 解决方案 废话不多说 我们直接给出解决方案 具体代码如下 import org s
  • Linux 线程同步的三种方法

    线程的最大特点是资源的共享性 但资源共享中的同步问题是多线程编程的难点 linux下提供了多种方式来处理线程同步 最常用的是互斥锁 条件变量和信号量 一 互斥锁 mutex 通过锁机制实现线程间的同步 初始化锁 在Linux下 线程的互斥量