Synchronizing STD cout output multi-thread

前端 未结 5 1167
梦毁少年i
梦毁少年i 2020-12-15 10:21

Latelly I\'ve been working with multi-thread coding, after a while writing I realized that if I used std::cout in different boost::threads, the output would came without a l

5条回答
  •  失恋的感觉
    2020-12-15 11:13

    You either need to impose an order on the threads so that the ordering of the output is as you want, (perhaps by passing thread-instances or events to the appropriate threads so that they can only execute in your order), or you could give all the outputs a thread-sequence number, queue all the outputs to one 'print' thread and, in there, keep a list of any out-of-order lines so that the printout is as you want.

    In the case of a 'real' app, (ie. not a trivial test app that misuses threads), where the threads do a lot of work in parallel on sequential buffers whose order must be preserved, forcing threads to wait for each other is not usually a reasonable option. It's usual to use sequence numbers and reassemble the buffer-stream afterwards.

提交回复
热议问题