I have many POSIX threads, two reader that read from serial port and others write to same port using a file descriptor. 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. (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. Maybe I’m asking wrong question. There should be a some kind of flush after each write() to make sure that device is free? or somehow force write() to block?
Clearly, the
EBUSYreturn code signals that the port is in use, and should be queried again later. 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. Each read/write would block the thread and avoid the
EBUSYproblem you are witnessing. All you would have left to do is implement a command queue (very easy withstd::queueor similar and just just one mutex to sync all accesses).UPDATE: reading your update, I guess that
EBUSYare 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. As I said at the beginning of my answer, have the thread wait a bit before reissuing its command, and that should do it.