【发布时间】:2014-01-23 12:27:07
【问题描述】:
好的,我正在使用 Mac 学习 c++11 中的多线程。据我所知,所有线程都是同时执行的。我从here找到以下代码
// thread example
#include <iostream> // std::cout
#include <thread> // std::thread
void foo()
{
std::cout << "\nIn foo \n";
}
void bar(int x)
{
std::cout << "\nIn bar \n";
}
int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar,0); // spawn new thread that calls bar(0)
std::cout << "main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
std::cout << "foo and bar completed.\n";
return 0;
}
每次我运行代码时,我都会得到以下示例的奇怪结果
米
aIIinnn ,bf aofroo o
和 bar 现在同时执行... foo 和 bar 已完成。
我错过了什么?
【问题讨论】:
-
这不是链接答案的副本。尽管有标题,但这里的 OP 并没有询问关于 std::cout 的一般性问题:他询问的是可以导致特定答案的特定问题(实际上是在结束之前提出的问题)。不应该作为重复关闭。至少不像以前那样。
标签: c++ multithreading c++11