我对visual c++中的并发编程有问题。下面代码中的线程一个接一个地执行,而不是同时执行所有线程。
#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;
}发布于 2014-03-18 15:45:41
您的线程是如此琐碎,以至于,当您开始第二个线程时,第一个线程正在进行中,或者已经完成。
另外,如果来自不同线程的cout输出不相互冲突,这并不意味着您的线程不同时运行,只意味着它可能受到某种(实现定义的)同步机制的保护。
如果你让它们花的时间更长,你可以看到它们在并行运行:
#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、->、->、并行堆栈/线程。
https://stackoverflow.com/questions/22483968
复制相似问题