C ++ 11多线程:显示到控制台 [英] C++11 Multithreading: Display to console

查看:245
本文介绍了C ++ 11多线程:显示到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个函数,它接受100个数据元素的数组,并将它们打印到控制台。

Consider a function that takes array of 100 data elements does something prints those to console.

现在我在多核机器上启动两个线程的函数。由于是多核机器,因此两个线程在两个内核上运行的概率很高。因为他们两个都需要显示数据,所以在控制台窗口中有一个竞争。

Now say I launch two threads of the function on a multicore machine. Since it's a multicore machine there is good probability that two threads run on two cores. Since both of them need to display data there's a race for console window.

现在控制台如何在线程之间共享。

Now how is the console shared between the threads.?

到达 std :: cout 的方法会显示整个数据,停止其他线程。
或者是控制台窗口在线程之间共享的时间。

The one which reaches the std::cout first gets to display entire data, stalling other thread .? or Is the console window time shared between threads.? if so what determines the amount of time sharing by the threads .?

推荐答案

不, cout 在C ++ 11中不是线程安全的。你必须自己安排。

No, cout is not threadsafe in C++11. You have to arrange that yourself.

[为了准确起见, cout 本身是线程安全的,但仅在调用本身的实际持续时间,一个典型的 cout < x<< y < endl; 将在 cout 对象中对成员函数进行三次不同的调用。所以你不需要为 cout 功能本身的互斥保护,但你确实需要它来保证调用 cout 作为一个单位执行]。

[To be accurate, cout itself is threadsafe, but only for the actual duration of the call itself, and a typical line of cout << x << y << endl; will be three different calls to member-function within the cout object. So you don't need mutex protection for the cout functionality itself, but you do need it to guarantee that a "line" of calls to cout are performed as one unit].

这篇关于C ++ 11多线程:显示到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆