【发布时间】:2014-01-17 12:41:34
【问题描述】:
我是 C++ 新手,我正在研究一些 C++ 跨平台线程教程。我正在调查这个:http://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/
并试图执行以下代码:
#include <iostream>
#include <thread>
static const int num_threads = 10;
//This function will be called from a thread
void call_from_thread(int tid) {
std::cout << "Launched by thread " << tid << std::endl;
}
int main() {
std::thread t[num_threads];
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
t[i] = std::thread(call_from_thread, i);
}
std::cout << "Launched from the main\n";
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
return 0;
}
我得到的输出如下,我不明白为什么:
syd@syd-HP-Compaq-dx7500-Microtower:~/Desktop$ ./ref
Launched by thread Launched by thread Launched by thread Launched by thread Launched by thread 201
Launched by thread 5
Launched by thread 6
4
Launched by thread 7
3
Launched by thread 8
Launched from the main
Launched by thread 9
我知道数字每次都是随机的,但有时我没有显示任何数字,我想知道为什么?
【问题讨论】:
-
std::cout << "something"没有逐行或operator<<调用同步。这就是为什么多个线程的输出可以交错的原因。 -
更准确地说,C++ 标准在 [iostreams.objects.overview]/4 中为标准流指定“并发访问同步标准 iostream 对象的格式化和未格式化输入和输出函数或标准多个线程的 C 流不应导致数据竞争。[注意:如果用户希望避免交错字符,则仍必须同步多个线程对这些对象和流的并发使用。- 结束注意 ]"
-
类似 std::string str = "Launched by thread " 然后 str.append(tid) 和 then 打印它会正常工作
-
@James:不是完全没用,只是有点不方便,迫使您在流式传输之前将整行(或您想要组合在一起的任何内容)格式化为单个字符串。如果您不关心类型安全或对用户定义类型的支持,
printf可能更方便。 -
@LanPac:这也不能保证。
标签: c++ multithreading c++11 iostream