C Multithreading – FIFO Lock with Multiple Threads/Processes

cmultithreading

I need to use FIFO in my application in linux+C, I have multiple threads and processes, I read some where that writing to a FIFO is atomic below some value (I believe 4k) especially I'm writing max of 300 bytes, Am I safe here?

Best Answer

It's atomic only inasmuch as how you write your FIFO queue/structure.

Wrapping a mutex or some other form of lock around the FIFO queue is probably the easiest way to guarantee concurrency and atomicity for the environment you describe.

If you'll have multiple processes attempting to write to the queue, then you'll probably need a dedicated handler for the queue.

Option A.

You could set up two write areas for the queue - the first area is where any and all processes can write to, synchronized with some sort of indexing scheme, or:

Option B.

It would probably be cleaner to have a dedicated process for the queue that has multiple threads to receive write requests. Synchronization on writing to the queue is then handled within the FIFO queue process itself.

As a rule, unless you have documentation in your hand that declares operation Foo to be thread-safe/atomic/whatever, then assume it isn't safe. Having "read somewhere ..." isn't going to cut it when you've got race conditions and the data in your queue has been shredded from simultaneous writes.

Option C.

Use the Pipe/FIFO structure provided by the OS.

Yes, you'll be fine/safe. From the first link on Pipes & FIFOs that you provided in the comments:

POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic:

And from the limits.h you linked:

 13 #define PIPE_BUF        4096    /* # bytes in atomic write to a pipe */

Since you're writing <= 300 bytes, and the POSIX minimum buffer size for an atomic write is 512 bytes, you're very much in the clear. To be paranoid, you could double check the PIPE_BUF size in your local limits.h, but it's not really necessary.

Your writes are guaranteed thread-safe since you're writing less than the pipe buffer size. Likewise, your reads should be okay and/or they should have the benefit of device locking preventing two threads from accessing at the same time.