从两个线程同时读取文件描述符 [英] simultaneous read on file descriptor from two threads

查看:103
本文介绍了从两个线程同时读取文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我的问题:在Linux(以及FreeBsd,通常是UNIX)中,是否可以同时从两个线程读取单个文件描述符?

  1. my question: in Linux (and in FreeBsd, and generally in UNIX) is it possible/legal to read single file descriptor simultaneously from two threads?

我进行了一些搜索,但没有找到任何答案,尽管很多人都问类似的问题,关于同时读取/写入套接字fd(意思是在写其他线程时进行读取,而不是在其他线程正在读取时进行读取)).我还阅读了一些手册页,但对我的问题没有明确的答案.

I did some search but found nothing, although a lot of people ask like question about reading/writing from/to socket fd at the same time (meaning reading when other thread is writing, not reading when other is reading). I also have read some man pages and got no clear answer on my question.

为什么要问.我试图实现一个简单的程序来计算stdin中的行数,例如wc -l.我实际上在测试自制的C ++ io引擎的开销,发现wc快了1.7倍.我修整了一些C ++,接近了wc速度,但没有达到.然后,我尝试了输入缓冲区的大小,对其进行了优化,但是wc显然要快一些.最终,我创建了2个线程,这些线程并行读取相同的STDIN_FILENO,这最终比wc快!但是行数变得不正确...所以我认为读取时会产生一些垃圾,这是意外的.内核不关心读取哪个进程吗?

Why I ask it. I tried to implement simple program that counts lines in stdin, like wc -l. I actually was testing my home-made C++ io engine for overhead, and discovered that wc is 1.7 times faster. I trimmed down some C++ and came closer to wc speed but didn't reach it. Then I experimented with input buffer size, optimized it, but still wc is clearly a bit faster. Finally I created 2 threads which read same STDIN_FILENO in parallel, and this at last was faster than wc! But lines count became incorrect... so I suppose some junk comes from reads which is unexpected. Doesn't kernel care what process read?

我做了一些研究,发现直接通过syscall调用read并不会改变任何东西.内核代码似乎进行了一些同步处理,但是我不太了解(read_write.c)

I did some research and discovered just that calling read directly via syscall does not change anything. Kernel code seem to do some sync handling, but i didnt understand much (read_write.c)

推荐答案

这是未定义的行为,

That's undefined behavior, POSIX says:

read()函数应尝试从文件读取nbyte字节与打开文件描述符fildes关联的缓冲区buf指向的.多个并发读取的行为未指定相同的管道,FIFO或终端设备.

The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified.

这篇关于从两个线程同时读取文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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