首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Visual c++并发编程

Visual c++并发编程
EN

Stack Overflow用户
提问于 2014-03-18 15:33:40
回答 1查看 186关注 0票数 1

我对visual c++中的并发编程有问题。下面代码中的线程一个接一个地执行,而不是同时执行所有线程。

代码语言:javascript
复制
#include "stdafx.h"
#include <iostream>
#include <thread>

using namespace std;

void f(){cout << "Hello ";}

struct F {
    void operator()(){ cout << "Parallel Word!\n"; }
};

void make_thread(){
    thread t1 {f};
    thread t2 {F()};

    t1.join();
    t2.join();
}

int _tmain(int argc, _TCHAR* argv[])
{
    make_thread();
    system("pause");
    return 0;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-18 15:45:41

您的线程是如此琐碎,以至于,当您开始第二个线程时,第一个线程正在进行中,或者已经完成。

另外,如果来自不同线程的cout输出不相互冲突,这并不意味着您的线程不同时运行,只意味着它可能受到某种(实现定义的)同步机制的保护。

如果你让它们花的时间更长,你可以看到它们在并行运行:

代码语言:javascript
复制
#include "stdafx.h"
#include <iostream>
#include <thread>

using namespace std;

void f() {
    for (int i = 0; i < 10; i++) {
        this_thread::sleep_for(chrono::milliseconds(100));
        cout << "Hello ";
    }
}

struct F {
    void operator()() {
        for (int i = 0; i < 10; i++) {
            this_thread::sleep_for(chrono::milliseconds(100));
            cout << "Parallel Word!\n";
        }
    }
};

void make_thread(){
    thread t1 {f};
    thread t2 {F()};

    t1.join();
    t2.join();
}

int _tmain(int argc, _TCHAR* argv[])
{
    make_thread();
    system("pause");
    return 0;
}

或者在线程创建后的某个地方放置一个断点,然后查看Debug、->、->、并行堆栈/线程。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22483968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档