简体   繁体   English

在线程之间共享文件描述符

[英]Share a file descriptor between threads

I have many POSIX threads, two reader that read from serial port and others write to same port using a file descriptor. 我有许多POSIX线程,两个读取器从串行端口读取,其他读取器使用文件描述符写入同一端口。 How can I share same descriptor between them? 我如何在它们之间共享相同的描述符? I have synchronized read/write and write/write actions between all threads by semaphores. 我已经通过信号量在所有线程之间同步了读/写和写/写操作。

Note: I'm supposing a file descriptor should be shared between threads of same process but my code fails to run with a EBUSY error when second reader tries to read from port. 注意:我假设文件描述符应该在同一进程的线程之间共享,但是当第二个读取器尝试从端口读取时,我的代码无法运行并出现EBUSY错误。 (asked a question before) (之前提出了一个问题

Update 更新资料

This is a little weird situation, even if only one thread is present at runtime, any call to read() after write() return -l with EBUSY error. 即使在运行时仅存在一个线程,这也是一种奇怪的情况,在write()之后对read()任何调用都将返回-l并带有EBUSY错误。 Maybe I'm asking wrong question. 也许我问错了问题。 There should be a some kind of flush after each write() to make sure that device is free? 在每个write()之后应该进行某种flush ,以确保该设备是空闲的? or somehow force write() to block? 还是以某种方式强制write()进行阻止?

Clearly, the EBUSY return code signals that the port is in use, and should be queried again later. 显然, EBUSY返回码表明该端口正在使用中,以后应再次查询。 Your threads should just wait a little bit and try again, until the command passes. 您的线程应该稍等片刻,然后重试,直到命令通过。

You sort of mention in one of your comments that the system behind the port is a mechanical one, which would explain why it could take a little while for a command to get processed. 您在其中的一条评论中提到了端口背后的系统是机械系统,这可以解释为什么处理命令可能要花一些时间。

I think the "one thread to handle IO" is the best approach. 我认为“一个处理IO的线程”是最好的方法。 Each read/write would block the thread and avoid the EBUSY problem you are witnessing. 每次读/写都会阻塞线程,并避免您看到的EBUSY问题。 All you would have left to do is implement a command queue (very easy with std::queue or similar and just just one mutex to sync all accesses). 您所要做的就是实现一个命令队列(使用std::queue或类似命令非常容易,并且只有一个互斥锁即可同步所有访问)。

UPDATE : reading your update, I guess that EBUSY are just the sign that commands are really slow to execute, and finish a little while after the system call returned, to the point that even when one single thread is doing IO, it may experience it. 更新 :阅读您的更新,我想EBUSY只是命令执行真的很慢的标志,并且在系统调用返回后完成一会儿,以至于即使单个线程正在执行IO,也可能会遇到这种情况。 As I said at the beginning of my answer, have the thread wait a bit before reissuing its command, and that should do it. 正如我在回答开始时所说的那样,让线程在重新发出命令之前稍等一下,然后应该这样做。

打开带有“ O_NONBLOCK”标志的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM