Multithreading: Read from / write to a pipe

Posted by Tero Jokinen on Stack Overflow See other posts from Stack Overflow or by Tero Jokinen
Published on 2009-11-11T02:25:13Z Indexed on 2010/05/13 8:04 UTC
Read the original article Hit count: 153

Filed under:
|
|

I write some data to a pipe - possibly lots of data and at random intervals. How to read the data from the pipe?

Is this ok:

  • in the main thread (current process) create two more threads (2, 3)
  • the second thread writes sometimes to the pipe (and flush-es the pipe?)
  • the 3rd thread has infinite loop which reads the pipe (and then sleeps for some time)

Is this so far correct?

Now, there are a few thing I don't understand:

  • do I have to lock (mutex?) the pipe on write?
  • IIRC, when writing to pipe and its buffer gets full, the write end will block until I read the already written data, right? How to check for read data in the pipe, not too often, not too rarely? So that the second thread wont block? Is there something like select for pipes?
  • It is possible to set the pipe to unbuffered more or I have to flush it regularly - which one is better?
  • Should I create one more thread, just for flushing the pipe after write? Because flush blocks as well, when the buffer is full, right? I just don't want the 1st and 2nd thread to block....

[Edit] Sorry, I thought the question is platform agnostic but just in case: I'm looking at this from Win32 perspective, possibly MinGW C...

© Stack Overflow or respective owner

Related posts about thread

Related posts about threading