C++ Multi-thread text output print to dos console

2019-09-16 07:59发布

问题:

I had a multi-thread program which execute from dos prompt, there are some prints and outputs dump to dos console using std::cout, but when thread1 and thread2 finished it jobs and then join() to main app, some printouts and outputs were overlapped and not aligned (no newline,running into each other).

Sometime they are ok. If you have some advises, I am really appreciate for your helps.

Andrew

回答1:

Well, it's simple. Output has no concurrency control, you're getting data races. You need to have your threads lock a mutex before they use output, then release it when they're done.



回答2:

I mean, I would expect them to overlap if they try to print to the same resource at the same time.

A common way to approach the problem of shared resources in multithreading is with a device called a mutex (http://en.wikipedia.org/wiki/Mutex), semaphore (http://en.wikipedia.org/wiki/Semaphore_(programming)) or simply a lock. When a thread wants to print, you have it grab the "lock token" and when it is done, release it. If the lock token is already taken, that thread will have to wait until it is available.

This is by no means a complete explanation but some reading to get background on the issue.



回答3:

As far as I know each individual << operator on cout is thread-safe. I have no reference to prove this though.

You can buffer the output in a stringstream object at then dump it to cout at one go (i.e using a single << operator)



回答4:

Writing to output is not thread-safe resulting in intermingled output. You need to synchronise access to standard output so that no more than one thread can write to output at the same time. Simplest approach is to use a mutex so one thread "takes ownership" of the standard output until it is done writing.