4

C++ 20 introduces a osyncstream (https://en.cppreference.com/w/cpp/io/basic_osyncstream) to synchronize threads writing to the same stream. But why there is no isyncstream to synchronize threads reading? Does this mean that reading are always be synchronized?

Thanks

Aamir
  • 1,974
  • 1
  • 14
  • 18
Wei Li
  • 1,847
  • 2
  • 10
  • 10
  • 3
    `osyncstream` is designed to stop interleaved output. You can't have interleaved input. – NathanOliver Jan 11 '23 at 15:55
  • Is that true? I can easily imagine a scenario where threads are fighting over new chunks as data as they're streamed to memory – Blindy Jan 11 '23 at 15:58
  • @Blindy From [here](https://en.cppreference.com/w/cpp/io/cin): *Unless sync_with_stdio(false) has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted input.* – NathanOliver Jan 11 '23 at 16:02
  • 3
    The answer to *"Why is X not in the standard?"* is almost always *"Because nobody has written a propsal for that"*. What would synced input mean? – BoP Jan 11 '23 at 16:03
  • @NathanOliver, you have the same exact line on `cout` as well, so I'm not sure it proves your point. – Blindy Jan 11 '23 at 16:19
  • 1
    @Blindy: Multiple output blocks can be prepared in parallel and then sequentially committed. Multiple input blocks have to be handled serially, since you have to find the end of the first block before you know the beginning of the next block. That's why database file formats use tricks like fixed-size records or indexes. Which support abstractions of random-access blocks... but cannot support an abstraction of a parallel synchronized single stream. – Ben Voigt Jan 11 '23 at 17:00

1 Answers1

1

Perhaps because multiple threads reading from a single stream does not make any sense.

Imagine that you have a sequence of messages being written to a stream and several, say 2 readers on the other side. Assume that each message is 1000 bytes long and 20 of those messages were written to the stream.

Now if thread #1 reads 600 bytes and sleeps waiting for the remaining 400 bytes to come across. Now, thread #2 wakes up and reads the remaining 400 bytes of the incoming message. Then thread #1 wakes up, blocks since thread #2 is reading and when it wakes up, reads another 400 bytes from the next message.

In the end, thread #1 have read 600 bytes of the first message and 400 bytes from the second message while thread #2 read 400 ending bytes of the first message. What are they going to do with the data? It just does not make any practical sense.

Something Something
  • 3,999
  • 1
  • 6
  • 21