C++多线程文本输出打印到 dos 控制台重叠/弄乱输出

发布于 2024-11-02 08:11:10 字数 185 浏览 2 评论 0原文

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

有时他们还好。如果您有任何建议,我非常感谢您的帮助。

安德鲁

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

飘过的浮云 2024-11-09 08:11:10

嗯,这很简单。输出没有并发控制,你会遇到数据竞争。您需要让线程在使用输出之前锁定互斥体,然后在完成后释放它。

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.

小鸟爱天空丶 2024-11-09 08:11:10

我的意思是,如果它们尝试同时打印到同一资源,我希望它们会重叠。

解决多线程中共享资源问题的一种常见方法是使用称为互斥体的设备(http://en .wikipedia.org/wiki/Mutex),信号量(http://en.wikipedia.org/wiki/Semaphore_(programming))或只是一个锁。当线程想要打印时,您可以让它获取“锁定令牌”,并在完成后释放它。如果锁令牌已被占用,则该线程将必须等待,直到它可用。

这绝不是完整的解释,而是一些阅读以了解该问题的背景。

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.

人心善变 2024-11-09 08:11:10

据我所知,每个人<< cout 上的运算符是线程安全的。不过我没有参考文献来证明这一点。

您可以将输出缓冲在 stringstream 对象中,然后一次性将其转储到 cout (即使用单个 << 运算符)

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)

傲世九天 2024-11-09 08:11:10

写入输出不是线程安全的,会导致输出混合。您需要同步对标准输出的访问,以便不超过一个线程可以同时写入输出。最简单的方法是使用互斥体,以便一个线程“取得标准输出的所有权”,直到完成写入为止。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文