C++新线程睡眠主线程

I G*_*att 0 c++ multithreading

运行以下代码:

methodOne(){
    std::thread t(&ChatBubble::runChatBubbleThread, this);
    t.join();
}
Run Code Online (Sandbox Code Playgroud)

runChatBubbleThread:

runChatBubbleThread(){
    // code here
    sleep(2000);
    // more code here    
}
Run Code Online (Sandbox Code Playgroud)

我的理解是新威胁t被创建,执行其代码,然后在主线程完成后加入主线程,有没有理由sleep()在主线程中休眠?

我唯一能想到的就是t.join在主线程继续之前等待线程完成,但是如果它必须等待则最后是线程的重点!

小智 7

目的thread.join是阻塞直到线程死亡.如果您想在等待新线程之前在主线程中执行某些操作,请先执行此操作join.