eventfd_write线程安全吗?

时间:2014-06-11 09:43:44

标签: c linux linux-kernel

如果我们有多次写入。作为事件id,编写线程安全性非常有用。文档没有说明线程安全性。

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.

1 个答案:

答案 0 :(得分:3)

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

write() / eventfd_write()返回时,eventfd的内部计数器保证会增加,但是当两个呼叫同时发生时,就不能保证他们的命令。 通过读取监视eventfd的第三个线程可能首先看到一个或另一个增量(或者它可能不够快并且只看到两个增量之后的总和)。

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

相关问题