Linux下使用eventfd实现进程间信号量操作

2024-02-02 21:38

本文主要是介绍Linux下使用eventfd实现进程间信号量操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1 前言

起源来自于单线程epoll_wait内部处理queue的思考,后来发现了linux支持一种自定义事件的fd,查找资料之余又发现了eventfd还有多进程信号灯的用处。。。本文翻译了eventfd的用法,并在文末附带demo进行实践。

2 介绍

eventfd 是 Linux 的一个系统调用,创建一个文件描述符用于事件通知,可在用户态编程使用。事件通知是基于计数器来实现,通过read、write实现计数器的加减。

2.1 eventfd

#include <sys/eventfd.h>
int eventfd(unsigned int initval, int flags);

该接口创建文件描述符fd,并按照initval初始化计数器。flags选项如下:

EFD_CLOEXEC (since Linux 2.6.27)Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor.   See  thedescription  of the O_CLOEXEC flag in open(2) for reasons why this may be use-ful.

open接口的O_CLOEXEC选项一样,表示在fork调用后,子进程继承所有父进程打开的文件描述符,这个选项再多进程中比较有用。

EFD_NONBLOCK (since Linux 2.6.27)Set the O_NONBLOCK file status flag on the new open file  description.   Usingthis flag saves extra calls to fcntl(2) to achieve the same result.

非阻塞选项,将影响read/write的调用结果。

EFD_SEMAPHORE (since Linux 2.6.30)Provide  semaphore-like semantics for reads from the new file descriptor.  Seebelow.

信号量选项,将影响read/write对计数器操作,详见2.2小节:

2.2 read

Each  successful  read(2) returns an 8-byte integer.
A read(2) will fail with the error EINVAL if the size of the supplied buffer is less than 8 bytes.

接口使用要求按8字节进行输入(u64的大小),否则抛EINVAL错误。

The value returned by read(2) is in host byte order-that is, 
the  native  byte order for integers on the host machine.

类似与网络操作,u64的输入是按照主机序进行,注意大小端问题。
另外,跟2.1小节选项相关的:

If EFD_SEMAPHORE was not specified and the eventfd counter has a nonzero value, 
then a read(2) returns  8  bytes  containing  that  value,  
and  the counter's value is reset to zero. 

如果没有设置EFD_SEMAPHORE,read接口表示从eventfd计数器读取8字节数据,数据值为计数器现有的值,读取完成后计数器将被重置成0。

If EFD_SEMAPHORE was specified and the eventfd counter has a nonzero value,
then a read(2) returns 8 bytes containing the value 1, 
and  the  counter's value is decremented by 1.

如果设置EFD_SEMAPHORE,read接口表示从eventfd计数器读取8字节数据,数据值一,读取完成后计数器减一操作。

If the eventfd counter is zero at the time of the call to read(2), 
then the all either blocks until the counter becomes nonzero (at  which  time,  
the read(2) proceeds as described above) or fails with the error EAGAIN if the file descriptor has been made nonblocking.

当计数器为0的时候,如果设置了阻塞选项,read调用将一直阻塞直到计数器变为非0状态,如果是非阻塞选项下,将会返回失败并抛errno=EAGAIN。

2.3 write

A write(2) call adds the 8-byte integer value supplied in its buffer to  the counter.
The maximum value that may be stored in the counter is the larges 
unsigned 64-bit value minus 1 (i.e.,  0xfffffffffffffffe).

write表示添加8字节的数值到计数器中,最大为MAX_U64 - 1。

If the addition would  cause  the  counter's  value  to  exceed the maximum, 
then the write(2) either blocks until a read(2) is performed on the file  descriptor,  
or fails with the error EAGAIN if the file descriptor has been made nonblocking.

如果超出上限,阻塞选项下将一直阻塞直到计数器的值被read走为止,非阻塞选项下将会返回失败并抛errno=EAGAIN。

3. 实践

3.1 样例


#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/eventfd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "common.h"#define WORKER_NUM 4
#define HAVE_SEMAPHORE 1int main(int argc, char *argv[])
{pid_t pid[WORKER_NUM] = {0};int res = -1;
#if HAVE_SEMAPHOREint fd = eventfd(0, EFD_SEMAPHORE | EFD_CLOEXEC | EFD_NONBLOCK);
#elseint fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
#endifassert(fd);for (int ix = 0; ix < WORKER_NUM; ix++) {pid[ix] = fork();if (pid[ix] < 0) {assert(0);}else if (pid[ix] > 0) {continue;}test_worker(fd);goto out;}test_master(fd);for (int ix = 0; ix < WORKER_NUM; ix++) {wait(NULL);}
out:close(fd);exit(EXIT_SUCCESS);
}

主函数中,将eventfd创建处理,并创建4个worker对应1个master,master一会用于增加计数器,worker进行计数器取值。注意使用了 HAVE_SEMAPHORE 控制,到时在第3.2小节说明现象的区别。

void test_master(int fd)
{
#if HAVE_SEMAPHOREu64 val = 1;
#elseu64 val = 1000;
#endifu64 sum = 0;for (int ix = 0; ix < 10; ix++) {assert(write(fd, &val, sizeof(val)) > 0);sum += val;printf("%x Send: %llu / %llu\n", (u32)getpid(), val, sum);usleep(100 * 1000);}
}

master中对计数器进行加操作,开启信号量模式 HAVE_SEMAPHORE 时为加一动作,否则加一堆。
注意eventfd只能使用 write进行操作,不能使用send接口。。
为了方便观察现象,master每次加计数器后进行短时休眠。

void test_worker(int fd)
{u64 sum = 0;int res = -1;for (int ix = 0; ix < 20; ix++) {u64 val = 0;res = read(fd, &val, sizeof(val));if (res < 0) {if (errno == EAGAIN) {usleep(100 * 1000);continue;}assert(0);}sum += val;printf("%x Recv: %llu / %llu\n", (u32)getpid(), val, sum);}printf("%x Recv sum: %llu quit...\n", (u32)getpid(), sum);
}

worker这块读取数值,并进行统计打印,由于使用了非阻塞选项,所以额外判断了eagain动作。为了方便阐述效果,使用睡眠+循环控制worker的超时退出动作。

3.2 结果分析

开启信号量模式,发现多个worker是轮流对计数器减一操作,存在相互竞争的关系,最终总数数值正确。同时试验了其他方式,worker也可以进行计数器加一操作,最终实现的是信号灯的效果。

1e92 Send: 1 / 1
1e94 Recv: 1 / 1
1e92 Send: 1 / 2
1e92 Send: 1 / 3
1e95 Recv: 1 / 1
1e95 Recv: 1 / 2
1e92 Send: 1 / 4
1e96 Recv: 1 / 1
1e92 Send: 1 / 5
1e92 Send: 1 / 6
1e93 Recv: 1 / 1
1e93 Recv: 1 / 2
1e92 Send: 1 / 7
1e93 Recv: 1 / 3
1e96 Recv: 1 / 2
1e92 Send: 1 / 8
1e92 Send: 1 / 9
1e94 Recv: 1 / 2
1e92 Send: 1 / 10
1e96 Recv: 1 / 3
1e93 Recv sum: 3 quit...
1e96 Recv sum: 3 quit...
1e95 Recv sum: 2 quit...
1e94 Recv sum: 2 quit...

没开启 EFD_SEMAPHORE,多个worker进程也存在相互竞争关系,由于master进行休眠控制,现象是1000、1000地读写。关闭休眠的时候,work的一次读取是会出现>1000动作的。

1ea5 Recv: 1000 / 1000
1e9d Send: 1000 / 1000
1e9d Send: 1000 / 2000
1ea6 Recv: 1000 / 1000
1e9d Send: 1000 / 3000
1ea6 Recv: 1000 / 2000
1e9d Send: 1000 / 4000
1ea4 Recv: 1000 / 1000
1e9d Send: 1000 / 5000
1ea6 Recv: 1000 / 3000
1ea6 Recv: 1000 / 4000
1e9d Send: 1000 / 6000
1e9d Send: 1000 / 7000
1ea4 Recv: 1000 / 2000
1e9d Send: 1000 / 8000
1ea4 Recv: 1000 / 3000
1e9d Send: 1000 / 9000
1ea3 Recv: 1000 / 1000
1e9d Send: 1000 / 10000
1ea3 Recv: 1000 / 2000
1ea6 Recv sum: 4000 quit...
1ea4 Recv sum: 3000 quit...
1ea3 Recv sum: 2000 quit...
1ea5 Recv sum: 1000 quit...

4. 结论

总体来讲,eventfd 功能是挺方便的,完美地将自定义事件与文件描述符结合起来。
内部的工作原理还缺少一下深入学习的地方。本文只列举了多进程的使用,而实际eventfd主要是用来跟epoll配合的,后续还需要再实践一下。

这篇关于Linux下使用eventfd实现进程间信号量操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/672048

相关文章

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详