multiple threads writing to std::cout or std::cerr

前端 未结 4 1358
醉话见心
醉话见心 2020-12-14 20:52

I have OpenMP threads that write to the console via cout and cerr. This of course is not safe, since output can be interleaved. I could do something like

#pr         


        
4条回答
  •  既然无缘
    2020-12-14 21:00

    As others pointed out, in C++11, std::cout is thread-safe.

    However if you use it like

    std::cout << 1 << 2 << 3;
    

    with different threads, the output can still be interleaved, since every << is a new function call which can be preceeded by any function call on another thread.

    To avoid interleaving without a #pragma omp critical - which would lock everything - you can do the following:

    std::stringstream stream; // #include  for this
    stream << 1 << 2 << 3;
    std::cout << stream.str();
    

    The three calls writing 123 to the stream are happening in only one thread to a local, non-shared object, therefore aren't affected by any other threads. Then, there is only one call to the shared output stream std::cout, where the order of items 123 is already fixed, therefore won't get messed up.

提交回复
热议问题