简体   繁体   中英

Synchronizing STD cout output in a boost::thread without control over threads

I want to ask exactly the same question as was asked here: Synchronizing STD cout output multi-thread with the single exception that i DO NOT have control over the code in which boost::thread s are used (that code is internal to this library , and I should not / want not to touch it, unless this problem can not be solved in any other way, in which case I could add it to my fork of the library.)

The library at a certain time spawns 4 threads (I'm on a mid-2010 MacBook Pro using OSX 10.10) in the C++ code that is executed in a single thread I use cout for logging, like so:

cout << "Writing file: " << "\\n" << xmlFileName << endl;

This output gets garbled due to multi-threading so it gets hard to understand what is going on in a single thread at any given moment...

How can I get the output synchronized ? The project uses Boost 1.57.0 so I can use that. I have never had to deal with multi-threading before but I understand the concepts and problems that arise. I have also seen some examples on SO but all of them require access to the code that spawns threads, either using a shared Mutex passed to the threads or using a lockGuard .

Although I have the feeling I can not escape modifying the library code, I hope that this is somehow possible?

  1. You could get extremely hacky and write a sycnhronizing stream buffer.

    You could then use that on the cout object:

     std::cout.rdbuf(new my_sync_cout_buf()); 

    before you start the threads.

    Note that this will require some amount of fidgeting to respond to flushes in a nice fashion. Doing this will break down if (one of the) threads uses std::unitbuf or std::flush liberally.

    In the absolute worst case you'd have to switch on thread id and interlace the output (eg line-by-line)

    THINKO: the ostream object itself would still be non-threadsafe. So it's just option #2 then, really:

  2. Perhaps it's easier (and saner) to just open pipes from one thread and read them from another. This way you can coordinate the order in which output is done yourself. Of course, since you don't control the threads, you'd have to fork instead of starting threads.

    Then, in each child process, you can setup the stream buffer of std::cout to write to the pipe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM