std :: thread().join()是否真的让线程同时运行?

tur*_*oup -1 c++ multithreading c++11

我需要一段代码来设置几个并发运行的线程,在它们全部完成之后,打印一些东西来通知用户.这是代码(在Windows上使用c ++ 11的库):

void func1(){
     int j = 0;
     while(j<=100000) j++;
}

int main(){
    for(int i = 0; i < 5; i++){
        std::thread t(func1);
        printf("releasing thread %d\n",i);
        t.join();
    printf("all threads finished\n");
    }   
}
Run Code Online (Sandbox Code Playgroud)

我认为这将使所有线程同时运行,但结果是它一次只运行一个线程,等到它完成,然后执行下一个线程.Outout:

releasing thread 0
releasing thread 1
releasing thread 2
releasing thread 3
releasing thread 4
all threads finished
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如果不分离线程,有什么意义的join()?我该怎么做才能实现我所描述的目标?

Kei*_*ith 6

请看这个例子.你必须启动所有线程,然后再加入它们.

http://www.cplusplus.com/reference/thread/thread/join/