C++20 信号(Signal)解析
头文件在C++20中是并发库技术规范(Technical Specification, TS)的一部分。信号量是同步原语,帮助控制多线程程序中对共享资源的访问。头文件提供了标准C++方式来使用信号量。
使用环境
Windows:VS中打开项目属性,修改C++语言标准。
Linux:GCC,版本至少应为10.1,编译命令中使用-std=c++20标志。
简单定义
你可以像这样创建一个信号量对象:
std::counting_semaphore<size_t> sem(1); // 用初始计数为1初始化一个信号量
std::counting_semaphore是一种允许指定数量的线程同时访问资源的信号量。在这个例子中,一次只有一个线程可以访问由sem保护的资源。
获取和释放
直接获取
要获取(锁定)信号量,你可以使用acquire方法:
sem.acquire();
// 关键段代码
sem.release();
acquire方法将信号量计数减一,有效地锁定它。release方法增加计数,释放信号量。
尝试获取
你也可以使用try_acquire方法来尝试获取信号量而不阻塞:
if (sem.try_acquire()) {
// 成功获取了信号量
// 关键段代码
sem.release();
} else {
// 信号量未被获取
}
带超时的等待
C++20还引入了try_acquire_for和try_acquire_until方法,以带超时的方式尝试获取信号量。
if (sem.try_acquire_for(std::chrono::seconds(1))) {
// 在1秒内成功获取了信号量
// 关键段代码
sem.release();
} else {
// 在1秒内未能获取信号量
}
信号量的类型
std::counting_semaphore
计数信号量是一种同步原语,允许多个线程在一定限制下访问共享资源。它是互斥锁或二进制信号量的泛化。
你可以用一个初始计数来初始化计数信号量,该计数代表可以同时无阻塞访问资源的线程数量。线程可以获取和释放计数,信号量的计数相应地增加或减少。如果线程尝试获取的计数超过了可用的数量,它将阻塞,直到计数变得可用。
// 展示如何使用counting_semaphore
#include <iostream>
#include <semaphore>
#include <thread>
using namespace std;
// 用3个计数初始化信号量
counting_semaphore<10> semaphore(3);
void worker(int id)
{
// 获取
semaphore.acquire();
// 执行一些工作
cout << "Thread " << id << " acquired the semaphore."
<< endl;
// 释放
semaphore.release();
cout << "Thread " << id << " released the semaphore."
<< endl;
}
int main()
{
thread t1(worker, 1);
thread t2(worker, 2);
thread t3(worker, 3);
t1.join();
t2.join();
t3.join();
return 0;
}
输出结果
Thread 2 acquired the semaphore.
Thread 2 released the semaphore.
Thread 1 acquired the semaphore.
Thread 1 released the semaphore.
Thread 3 acquired the semaphore.
Thread 3 released the semaphore.
std::binary_semaphore
二进制信号量是一种更简单的信号量版本,它只能有两个值:0和1。
通常用于两个线程之间的基本互斥或信号传递。可以被视为具有更轻量级接口的互斥锁。类似于mutex。
// 展示二进制信号量的用法
#include <iostream>
#include <semaphore>
#include <thread>
using namespace std;
// 用1个计数(二进制)初始化信号量
binary_semaphore semaphore(1);
void worker(int id)
{
// 获取信号量
semaphore.acquire();
cout << "Thread " << id << " acquired the semaphore."
<< endl;
// 执行一些工作
semaphore.release();
// 释放信号量
cout << "Thread " << id << " released the semaphore."
<< endl;
}
int main()
{
thread t1(worker, 1);
thread t2(worker, 2);
t1.join();
t2.join();
return 0;
}
输出结果
Thread 1 acquired the semaphore.
Thread 1 released the semaphore.
Thread 2 acquired the semaphore.
Thread 2 released the semaphore.
优点
信号量的优势如下:
- 精细控制:信号量可以配置为允许特定数量的线程同时访问资源,实现资源的精细控制。
- 通用性:信号量更加灵活多样,可以用来实现其他同步原语。
- 多资源管理:计数信号量可以用来管理多个资源实例,适用于需要控制对资源池(如线程池或连接池)访问的场景。
- 阻塞等待:信号量中的阻塞和等待机制允许线程等待直到资源再次可用。
- 超时处理:在获取信号量时可以指定超时,使其更加实用。
例子:生产者消费者问题
#include <iostream>
#include <semaphore>
#include <thread>
using namespace std;
const int buffer_size = 5;// 缓冲区大小
std::binary_semaphore b_mutex(1);
//容量为5 赋初值
std::counting_semaphore<buffer_size> b_full(0);
std::counting_semaphore<buffer_size> b_empty(5);
void Producer()
{
while (true)
{
b_empty.acquire();
b_mutex.acquire();
std::cout << "Producer\n";
b_mutex.release();
b_full.release();
//模拟生成过程
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
void Consumer()
{
while (true)
{
b_full.acquire();
b_mutex.acquire();
std::cout << "Consumer\n";
b_mutex.release();
b_empty.release();
//模拟消耗过程
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
int main()
{
thread t0(Producer);
thread t1(Producer);
thread t2(Consumer);
thread t3(Consumer);
t0.join();
t1.join();
t2.join();
t3.join();
}
关键组件
b_mutex:一个二进制信号量,用作互斥锁,保证在任何时刻只有一个线程可以操作缓冲区。这是为了防止多个生产者或消费者同时访问缓冲区,导致数据不一致的问题。
b_full:一个计数信号量,表示缓冲区中已填充的项数。初始化为0,因为一开始缓冲区是空的。
b_empty:另一个计数信号量,表示缓冲区中空闲位置的数量。初始化为缓冲区的大小,因为起初整个缓冲区都是空的。
生产者(Producer)
等待一个空闲位置(b_empty.acquire();),这表示生产者在缓冲区中找到了一个可以放置新生产项的位置。
获取互斥锁(b_mutex.acquire();),进行生产操作(这里通过打印"Producer"模拟),然后释放互斥锁(b_mutex.release();),这样其他线程(生产者或消费者)就可以访问缓冲区了。
生产完成后,释放一个已满位置的信号(b_full.release();),告知消费者缓冲区中有项可被消费。模拟生产过程中的延迟(std::this_thread::sleep_for(std::chrono::seconds(2));)。
消费者(Consumer)
等待一个已满位置(b_full.acquire();),这表示消费者在缓冲区中找到了一个可以消费的项。
获取互斥锁(b_mutex.acquire();),进行消费操作(这里通过打印"Consumer"模拟),然后释放互斥锁(b_mutex.release();),这样其他线程(生产者或消费者)就可以访问缓冲区了。
消费完成后,释放一个空闲位置的信号(b_empty.release();),告知生产者缓冲区中有位置可用于生产新的项。模拟消费过程中的延迟(std::this_thread::sleep_for(std::chrono::seconds(2));)。
上一篇: 微信识别二维码是限制版 - 掘金
下一篇: 算法入门练习 8.19 风筝图
推荐阅读
-
C++20 信号(Signal)解析
-
安卓跨进程通信信号(Signal)
-
阅读笔记:《基于WiFi信号的人类活动识别理解与建模》(Understanding and Modeling of WiFi Signal Based Human Activity Recognition
-
windows下进程间通信的(13种方法)-摘 要 本文讨论了进程间通信与应用程序间通信的含义及相应的实现技术,并对这些技术的原理、特性等进行了深入的分析和比较。 ---- 关键词 信号 管道 消息队列 共享存储段 信号灯 远程过程调用 Socket套接字 MQSeries 1 引言 ---- 进程间通信的主要目的是实现同一计算机系统内部的相互协作的进程之间的数据共享与信息交换,由于这些进程处于同一软件和硬件环境下,利用操作系统提供的的编程接口,用户可以方便地在程序中实现这种通信;应用程序间通信的主要目的是实现不同计算机系统中的相互协作的应用程序之间的数据共享与信息交换,由于应用程序分别运行在不同计算机系统中,它们之间要通过网络之间的协议才能实现数据共享与信息交换。进程间通信和应用程序间通信及相应的实现技术有许多相同之处,也各有自己的特色。即使是同一类型的通信也有多种的实现方法,以适应不同情况的需要。 ---- 为了充分认识和掌握这两种通信及相应的实现技术,本文将就以下几个方面对这两种通信进行深入的讨论:问题的由来、解决问题的策略和方法、每种方法的工作原理和实现、每种实现方法的特点和适用的范围等。 2 进程间的通信及其实现技术 ---- 用户提交给计算机的任务最终都是通过一个个的进程来完成的。在一组并发进程中的任何两个进程之间,如果都不存在公共变量,则称该组进程为不相交的。在不相交的进程组中,每个进程都独立于其它进程,它的运行环境与顺序程序一样,而且它的运行环境也不为别的进程所改变。运行的结果是确定的,不会发生与时间相关的错误。 ---- 但是,在实际中,并发进程的各个进程之间并不是完全互相独立的,它们之间往往存在着相互制约的关系。进程之间的相互制约关系表现为两种方式: ---- (1) 间接相互制约:共享CPU ---- (2) 直接相互制约:竞争和协作 ---- 竞争——进程对共享资源的竞争。为保证进程互斥地访问共享资源,各进程必须互斥地进入各自的临界段。 ---- 协作——进程之间交换数据。为完成一个共同任务而同时运行的一组进程称为同组进程,它们之间必须交换数据,以达到协作完成任务的目的,交换数据可以通知对方可以做某事或者委托对方做某事。 ---- 共享CPU问题由操作系统的进程调度来实现,进程间的竞争和协作由进程间的通信来完成。进程间的通信一般由操作系统提供编程接口,由程序员在程序中实现。UNIX在这个方面可以说最具特色,它提供了一整套进程间的数据共享与信息交换的处理方法——进程通信机制(IPC)。因此,我们就以UNIX为例来分析进程间通信的各种实现技术。 ---- 在UNIX中,文件(File)、信号(Signal)、无名管道(Unnamed Pipes)、有名管道(FIFOs)是传统IPC功能;新的IPC功能包括消息队列(Message queues)、共享存储段(Shared memory segment)和信号灯(Semapores)。 ---- (1) 信号 ---- 信号机制是UNIX为进程中断处理而设置的。它只是一组预定义的值,因此不能用于信息交换,仅用于进程中断控制。例如在发生浮点错、非法内存访问、执行无效指令、某些按键(如ctrl-c、del等)等都会产生一个信号,操作系统就会调用有关的系统调用或用户定义的处理过程来处理。 ---- 信号处理的系统调用是signal,调用形式是: ---- signal(signalno,action) ---- 其中,signalno是规定信号编号的值,action指明当特定的信号发生时所执行的动作。 ---- (2) 无名管道和有名管道 ---- 无名管道实际上是内存中的一个临时存储区,它由系统安全控制,并且独立于创建它的进程的内存区。管道对数据采用先进先出方式管理,并严格按顺序操作,例如不能对管道进行搜索,管道中的信息只能读一次。 ---- 无名管道只能用于两个相互协作的进程之间的通信,并且访问无名管道的进程必须有共同的祖先。 ---- 系统提供了许多标准管道库函数,如: pipe——打开一个可以读写的管道; close——关闭相应的管道; read——从管道中读取字符; write——向管道中写入字符; ---- 有名管道的操作和无名管道类似,不同的地方在于使用有名管道的进程不需要具有共同的祖先,其它进程,只要知道该管道的名字,就可以访问它。管道非常适合进程之间快速交换信息。 ---- (3) 消息队列(MQ) ---- 消息队列是内存中独立于生成它的进程的一段存储区,一旦创建消息队列,任何进程,只要具有正确的的访问权限,都可以访问消息队列,消息队列非常适合于在进程间交换短信息。 ---- 消息队列的每条消息由类型编号来分类,这样接收进程可以选择读取特定的消息类型——这一点与管道不同。消息队列在创建后将一直存在,直到使用msgctl系统调用或iqcrm -q命令删除它为止。 ---- 系统提供了许多有关创建、使用和管理消息队列的系统调用,如: ---- int msgget(key,flag)——创建一个具有flag权限的MQ及其相应的结构,并返回一个唯一的正整数msqid(MQ的标识符); ---- int msgsnd(msqid,msgp,msgsz,msgtyp,flag)——向队列中发送信息; ---- int msgrcv(msqid,cmd,buf)——从队列中接收信息; ---- int msgctl(msqid,cmd,buf)——对MQ的控制操作; ---- (4) 共享存储段(SM) ---- 共享存储段是主存的一部分,它由一个或多个独立的进程共享。各进程的数据段与共享存储段相关联,对每个进程来说,共享存储段有不同的虚拟地址。系统提供的有关SM的系统调用有: ---- int shmget(key,size,flag)——创建大小为size的SM段,其相应的数据结构名为key,并返回共享内存区的标识符shmid; ---- char shmat(shmid,address,flag)——将当前进程数据段的地址赋给shmget所返回的名为shmid的SM段; ---- int shmdr(address)——从进程地址空间删除SM段; ---- int shmctl (shmid,cmd,buf)——对SM的控制操作; ---- SM的大小只受主存限制,SM段的访问及进程间的信息交换可以通过同步读写来完成。同步通常由信号灯来实现。SM非常适合进程之间大量数据的共享。 ---- (5) 信号灯 ---- 在UNIX中,信号灯是一组进程共享的数据结构,当几个进程竞争同一资源时(文件、共享内存或消息队列等),它们的操作便由信号灯来同步,以防止互相干扰。 ---- 信号灯保证了某一时刻只有一个进程访问某一临界资源,所有请求该资源的其它进程都将被挂起,一旦该资源得到释放,系统才允许其它进程访问该资源。信号灯通常配对使用,以便实现资源的加锁和解锁。 ---- 进程间通信的实现技术的特点是:操作系统提供实现机制和编程接口,由用户在程序中实现,保证进程间可以进行快速的信息交换和大量数据的共享。但是,上述方式主要适合在同一台计算机系统内部的进程之间的通信。 3 应用程序间的通信及其实现技术 ---- 同进程之间的相互制约一样,不同的应用程序之间也存在竞争和协作的关系。UNIX操作系统也提供一些可用于应用程序之间实现数据共享与信息交换的编程接口,程序员可以通过自己编程来实现。如远程过程调用和基于TCP/IP协议的套接字(Socket)编程。但是,相对普通程序员来说,它们涉及的技术比较深,编程也比较复杂,实现起来困难较大。 ---- 于是,一种新的技术应运而生——通过将有关通信的细节完全掩盖在某个独立软件内部,即底层的通讯工作和相应的维护管理工作由该软件内部来实现,用户只需要将通信任务提交给该软件去完成,而不必理会它的具体工作过程——这就是所谓的中间件技术。 ---- 我们在这里分别讨论这三种常用的应用程序间通信的实现技术——远程过程调用、会话编程技术和MQSeries消息队列技术。其中远程过程调用和会话编程属于比较低级的方式,程序员参与的程度较深,而MQSeries消息队列则属于比较高级的方式,即中间件方式,程序员参与的程度较浅。 ---- 4.1 远程过程调用(RPC)
-
详解DDR内存工作机制:DQ和DQS信号的解析与操作
-
VoLTE 信号通话解析指南
-
探究Simulink建模与仿真的信号线上各类图标的详细解析
-
理解信号处理:入门篇 - 傅里叶级数详解之周期序列的解析
-
梳理傅立叶信号的相关技巧:信号解析与处理简述
-
信号与系统实战指南:(15)非周期信号的频域解析 - 傅里叶变换深入浅出第二部:傅里叶变换详解