简体   繁体   English

C ++多线程文本输出打印到Dos控制台重叠/缺少输出

[英]C++ Multi-thread text output print to dos console overlapped/Mess up the outputs

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). 我有一个从dos提示符执行的多线程程序,使用std :: cout有一些打印和输出转储到dos控制台,但是当thread1和thread2完成它的工作,然后join()到主应用程序时,一些打印输出和输出重叠且未对齐(没有换行符,互相碰到)。

Sometime they are ok. 有时候他们还好。 If you have some advises, I am really appreciate for your helps. 如果您有什么建议,非常感谢您的帮助。

Andrew 安德鲁

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. 您需要让线程在使用输出之前锁定互斥量,然后在完成操作后将其释放。

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. 解决多线程共享资源问题的一种常见方法是使用称为互斥体( http://en.wikipedia.org/wiki/Mutex ),信号量( http://en.wikipedia.org/wiki/Semaphore_ (编程) )或只是一个锁。 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. 这绝不是一个完整的解释,而是一些阅读来获取有关此问题的背景知识。

As far as I know each individual << operator on cout is thread-safe. 据我所知,cout上的每个单独的<<操作符都是线程安全的。 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 (ie using a single << operator) 您可以将输出缓冲在stringstream对象中,然后将其一次性转储到cout(即使用单个<<操作符)

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. 最简单的方法是使用互斥锁,以便一个线程“拥有”标准输出,直到完成写入为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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