关于 C++多线程的一个问题

2015-06-20 22:14:06 +08:00
 n0o0a0h0

现在学长让我把一个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里面编译的哦。
感谢各位指导。如果能指引一下多线程的方向就更感谢啦!

1727 次点击
所在节点    C
18 条回复
aheadlead
2015-06-20 22:16:56 +08:00
xdeng
2015-06-20 23:10:25 +08:00
0o0 按理说是一次性输出的
limhiaoing
2015-06-20 23:48:15 +08:00
你看的那篇文章里写了这么一句话
Actually if you run the above code on your system you can get a completely different result or even some mangled characters.
limhiaoing
2015-06-20 23:50:55 +08:00
我也写过一篇关于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等
zonyitoo
2015-06-21 00:03:15 +08:00
乱掉很正常,你给的例子里它也是乱掉的,只是没有你的这么乱罢了。
多线程同时调用cout,没有人能知道它到底是以什么样的顺序进入到cout的buffer里面。
正确的姿势是用Mutex锁住cout。
n0o0a0h0
2015-06-21 00:06:25 +08:00
@limhiaoing 谢谢 你的blog 写得好详细 我细细品味一下
@aheadlead
@zonyitoo
谢谢两位 我是初学者啦~~~
@xdeng 可以参考楼上的回答
xdeng
2015-06-21 00:30:38 +08:00
原来是c++11 自带的线程
aheadlead
2015-06-21 01:01:46 +08:00
@n0o0a0h0 加油!
secondwtq
2015-06-21 01:11:24 +08:00
我在 Linux 下测试,结果和原文差不多。
在 Mac 下测试,结果和楼主给的差不多。
SoloCompany
2015-06-21 01:55:45 +08:00
头像好萌
chlx
2015-06-21 02:07:15 +08:00
即使满足sequential order也是乱掉的。 同楼上, 锁住cout
middleware
2015-06-21 08:22:41 +08:00
iostream 自己有同步。由 sync_with_stdio() 控制。
shimoyo
2015-06-21 10:01:22 +08:00
前段时间的操作系统课讲的进程的互斥,老师讲的例子几乎和这个一样……
inevermore
2015-06-21 13:33:35 +08:00
你们啊,naive,最简单的方式是使用printf,他是默认原子性的。
n0o0a0h0
2015-06-21 17:16:21 +08:00
@chlx 锁定了哦 不知道是否可以控制thread输出的是顺序呢?
n0o0a0h0
2015-06-21 17:16:40 +08:00
@inevermore 其实也是初学这方面 ~~多谢批评
Axurez
2015-06-22 00:29:00 +08:00
cppreference 的例子说了,Possible output (order of lines may vary, but they are never intermingled)
并不是顺序的
n0o0a0h0
2015-06-22 10:08:19 +08:00
@Axurez 好的~~~ 谢谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/200093

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX