eventfd_write线程安全吗? [英] Is eventfd_write thread safe?

查看:641
本文介绍了eventfd_write线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有多次写入.作为事件ID,编写线程安全性确实很有用.文档未提及线程安全性.

If we have multiple writes. As an event id, writing thread safety is really useful. Document does not say anything about thread safety.

Additional glibc features
       The GNU C library defines an additional type, and two functions that attempt  to  abstract
       some of the details of reading and writing on an eventfd file descriptor:

       typedef uint64_t eventfd_t;

       int eventfd_read(int fd, eventfd_t *value);
       int eventfd_write(int fd, eventfd_t value);

       The functions perform the read and write operations on an eventfd file descriptor, return-
       ing 0 if the correct number of bytes was transferred, or -1 otherwise.

推荐答案

写入eventfd是线程安全的,即,允许两个线程(甚至进程)同时写入相同的fd,并且它们将正确序列化.

Writing to an eventfd is thread safe, i.e., two threads (or even processes) are allowed to write to the same fd at the same time, and they will be properly serialized.

write()/eventfd_write()返回时,可以保证增加了eventfd的内部计数器,但是当同时发生两个调用时,它们的顺序将无法保证. 通过读取来监视eventfd的第三个线程可能会首先看到一个或另一个增量(或者它可能不够快,在两个增量之后只能看到总和).

The eventfd's internal counter is guaranteed to have been increased when write()/eventfd_write() returns, but when two calls happen at the same time, there can be no gurantee about their order. A third thread that monitors the eventfd by reading it might see one or the other increment first (or it might not be fast enough and see only the sum after both increments).

当您调用write(fd, &value, 8)时,另一个线程同时修改了value变量时,您无法预测增量将使用旧值还是新值(或两者的组合,如果修改为不是原子的).但是,从该内存读取并用于增量的实际值将保持一致.

When you are calling write(fd, &value, 8), and another thread modifies the value variable at the same time, you cannot predict whether the increment will use the old or the new value (or a combination of both, if the modification isn't atomic). However, the actual value read from that memory and used for the increment will be consistent.

这篇关于eventfd_write线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆