C++ std::thread().join()真的使线程并发运行吗?
我需要一段代码来设置两个线程并发运行,在它们全部完成后,打印一些东西来通知用户。下面是代码(在Windows上使用c++11的库):C++ std::thread().join()真的使线程并发运行吗?,c++,multithreading,c++11,C++,Multithreading,C++11,我需要一段代码来设置两个线程并发运行,在它们全部完成后,打印一些东西来通知用户。下面是代码(在Windows上使用c++11的库): 在这种情况下,如果join()不分离线程,那么它有什么意义呢?我应该做些什么来实现我描述的目标 请看这个例子。您必须启动所有线程,然后稍后“加入”它们 要回答第二个问题,如果没有join()调用,线程将同时运行,但没有内置的数据竞争保护,这是您需要解决的问题。显示的代码不会生成显示的输出。您的{放错了位置 #include <thread> #incl
在这种情况下,如果join()不分离线程,那么它有什么意义呢?我应该做些什么来实现我描述的目标 请看这个例子。您必须启动所有线程,然后稍后“加入”它们
要回答第二个问题,如果没有
join()
调用,线程将同时运行,但没有内置的数据竞争保护,这是您需要解决的问题。显示的代码不会生成显示的输出。您的{
放错了位置
#include <thread>
#include <vector>
#include <iostream>
void func1(int i){
int j = 0;
while(j<=100000) j++;
std::cout << "thread " << i << " finished\n";
}
int main(){
std::vector<std::thread> threads;
try {
for(int i = 0; i < 5; i++){
threads.push_back(std::thread(func1, i));
}
} catch (...) {
}
for( std::thread& t : threads ) {
t.join();
}
std::cout << "all threads finished\n";
}
但是,请注意,MSVC 2012和2013std::async
不符合标准,并且上述代码对其也不安全
一般来说,您应该将线程原语包装在自己的RAII包装器中,以备不时之需。。为什么一个名为join的方法会被分离threads@aaronman因为根据这个:join使线程分开执行。如果我错了,请纠正我使用两个for循环和一个线程向量。我想你会更高兴您在发布的代码中所做的只是启动一个线程,然后等待它完成,然后再启动下一个线程。瞧,您有一个非常昂贵的函数调用。
所有已完成的线程应在输出窗口中显示5次。您应该更正
releasing thread 0
releasing thread 1
releasing thread 2
releasing thread 3
releasing thread 4
all threads finished
#include <thread>
#include <vector>
#include <iostream>
void func1(int i){
int j = 0;
while(j<=100000) j++;
std::cout << "thread " << i << " finished\n";
}
int main(){
std::vector<std::thread> threads;
try {
for(int i = 0; i < 5; i++){
threads.push_back(std::thread(func1, i));
}
} catch (...) {
}
for( std::thread& t : threads ) {
t.join();
}
std::cout << "all threads finished\n";
}
void func1(int i){
int j = 0;
while(j<=100000) j++;
std::cout << "thread " << i << " finished\n";
}
int main(){
std::vector<std::future> threads;
try {
for(int i = 0; i < 5; i++){
threads.push_back(std::async(func1, i));
}
}
for( std::future& f : threads ) {
f.wait();
}
std::cout << "all threads finished\n";
}