Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I finally found the culprit. If you search for Internet a lot of sites recommends using the sync_with_stdio call, but they don't talk about threads.</p> <p>Other sites talk about iostreams and threads, like <a href="https://stackoverflow.com/questions/6374264/is-cout-synchronized-thread-safe">this one</a>, but that doesn't explain why I was getting corrupted output when I was using std::cin in <strong>only one thread</strong>, and std::cout <strong>in its own thread too</strong>.</p> <p>The problem is that internally, the std::cin input thread was calling to std::cout to flush its buffer, but as the streams where not synchronized with mutex or something similar, the output was corrupted. Why should I synchronized the buffers if they are doing different things? Why std::cin was messing with std::cout?</p> <p>In C++, by default, the standard streams cin, cerr and clog are tied to cout. What does this mean? It means that when you try to read from cin, first it will force a flush to cout. Sometimes this is something useful as you can read <a href="https://stackoverflow.com/questions/2704752/flushing-of-cout-prior-to-reading-input-using-cin-why">here</a>.</p> <p>But in my case, this was causing some serious issues, so, how to untie the streams?. It's very easy using the <a href="http://en.cppreference.com/w/cpp/io/basic_ios/tie" rel="nofollow noreferrer"><strong>tie method</strong></a>:</p> <pre><code>std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cerr.tie(nullptr); </code></pre> <p>Or if your compiler doesn't support C++11:</p> <pre><code>std::ios_base::sync_with_stdio(false); std::cin.tie(static_cast&lt;ostream*&gt;(0)); std::cerr.tie(static_cast&lt;ostream*&gt;(0)); </code></pre> <p>With this changes my output it's now correct:</p> <pre><code>Packet id = 1 Packet id = 2 Packet id = 3 Packet id = 4 Packet id = 5 Packet id = 6 Packet id = 7 Packet id = 8 Packet id = 9 Packet id = 10 </code></pre> <p>And as it avoids doing a flush every time std::cin is used, it's faster too :-)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload