避免不同线程发生阻塞冲突的简单方法?
我有一个多线程程序,其中两个单独的线程将调试输出发送到 std::clog 并且输出是分散的。我想找到一种简单的方法来强制输出至少保持独立,除了输出中的换行符。这样,可以更容易地解释调试输出。在某些地方,我在输出之前插入了 sleep(1) 并将输出收集到字符串中,然后将其发送到 clog 以减少冲突的机会,但我更喜欢更强大且可靠的解决方案。
有没有一种简单的方法可以确保每个线程在另一个线程进入并写入自己的输出行之前一次将整行写入 std::clog ?
I have a multi-threaded program where two separate threads are sending debug output to std::clog and the outputs are interspersed. I would like to find an easy way to force the output to at least be kept separate except at line feeds in the output. This way, the debug output can be more readily interpreted. In some places, I've inserted a sleep(1) before the output and gather up the output into a string before sending it to clog to reduce the chances of collision, but I'd prefer a more robust and sure fired solution.
Is there an easy way to ensure that each thread writes a whole line at a time to std::clog before the other thread can get in and write its own line of output?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有特别简单的方法可以做到这一点,这里有一个关于它的扩展讨论:http:// www.cplusplus.com/forum/general/27760/
通过创建一个新的
AtomicStream
,在传输其他任何内容之前,该问题以原子方式写入整行(这是通过缓冲技巧完成的)。您需要想出一个类似的解决方案。对于这个不容易回答的问题感到抱歉——线程同步必须以某种方式纳入您的解决方案中。这可能是衍生的,但如果您的 std::clog 重定向到一个文件,您也可以为多个线程拥有多个文件。
There's no particularly easy way of doing this, and there's an extended discussion about it here: http://www.cplusplus.com/forum/general/27760/
The problem is somewhat solved there with the creation of a new
AtomicStream
that writes an entire line atomically, before anything else is streamed (this is done with buffering tricks). You'll need to come up with a similar solution. Sorry for the non-easy answer -- thread synchronization will somehow have to make it into your solution.This may be derivative, but if your
std::clog
redirects to a file, you could also have multiple files for the multiple threads.你……不能。您同时写入同一个流。
clog
中的缓冲会有所帮助,但仍然不能保证。除非您想同步线程的日志记录(对于您正在做的事情来说有点昂贵),否则您应该考虑使用日志记录工具(这将允许您记录不同的文件用于不同的事情)。
You ... can't. You're writing to the same stream at the same time. The buffering in
clog
will help a little, but there's still no guarantees.Unless you want to synchronize your threads' logging (kinda expensive for what you're doing) maybe you should look at using a logging facility instead (this would allow you to log to say, different files for different things).
是的,您正在寻找跨线程同步方法。这些通常可以在操作系统的 API 中找到,您也可以在 Boost 中找到一个。
Yeah, you're lookign for a cross-thread synchronization method. These are usually available in an operating system's API, you can also find one in Boost.