现在学长让我把一个1300多行的代码改成多线程,%>_<%,然后开始看了一些多线程的指导,链接在此
有一个例子如下所示:
#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;
}
例子说它的输出应该为:

但是我的输出确实乱掉的:

我是在xcode里面编译的哦。
感谢各位指导。如果能指引一下多线程的方向就更感谢啦!
1
aheadlead 2015 年 6 月 20 日
|
2
xdeng 2015 年 6 月 20 日
0o0 按理说是一次性输出的
|
3
limhiaoing 2015 年 6 月 20 日
你看的那篇文章里写了这么一句话
Actually if you run the above code on your system you can get a completely different result or even some mangled characters. |
4
limhiaoing 2015 年 6 月 20 日
我也写过一篇关于C++11 多线程的简单的入门文章
http://blog.poxiao.me/p/multi-threading-in-cpp11-part-1-thread-and-future/ 涉及到 std::thread std::future std::async std::promise std::packaged_task等 |
5
zonyitoo 2015 年 6 月 21 日
乱掉很正常,你给的例子里它也是乱掉的,只是没有你的这么乱罢了。
多线程同时调用cout,没有人能知道它到底是以什么样的顺序进入到cout的buffer里面。 正确的姿势是用Mutex锁住cout。 |
6
n0o0a0h0 OP |
7
xdeng 2015 年 6 月 21 日
原来是c++11 自带的线程
|
9
secondwtq 2015 年 6 月 21 日
我在 Linux 下测试,结果和原文差不多。
在 Mac 下测试,结果和楼主给的差不多。 |
10
SoloCompany 2015 年 6 月 21 日
头像好萌
|
11
chlx 2015 年 6 月 21 日
即使满足sequential order也是乱掉的。 同楼上, 锁住cout
|
12
middleware 2015 年 6 月 21 日
iostream 自己有同步。由 sync_with_stdio() 控制。
|
13
shimoyo 2015 年 6 月 21 日 via iPhone
前段时间的操作系统课讲的进程的互斥,老师讲的例子几乎和这个一样……
|
14
inevermore 2015 年 6 月 21 日
你们啊,naive,最简单的方式是使用printf,他是默认原子性的。
|
16
n0o0a0h0 OP @inevermore 其实也是初学这方面 ~~多谢批评
|
17
Axurez 2015 年 6 月 22 日
cppreference 的例子说了,Possible output (order of lines may vary, but they are never intermingled)
并不是顺序的 |