c++新线程休眠主线程

C++ new thread sleeps main thread

本文关键字:线程 休眠 新线程 c++      更新时间:2023-10-16

运行以下代码:

methodOne(){
    std::thread t(&ChatBubble::runChatBubbleThread, this);
    t.join();
}

runChatBubbleThread:

runChatBubbleThread(){
    // code here
    sleep(2000);
    // more code here    
}

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

我唯一能想到的是t.join正在等待线程完成,然后它继续在主线程上,但是如果它必须等待,线程的意义是什么!

thread.join的目的是阻塞直到线程死亡。如果您想在等待新线程之前在主线程中做一些事情,请在join之前完成。

有几个简单的方法。

jwde覆盖第一个

void methodOne(){
    std::thread t(&ChatBubble::runChatBubbleThread, this);
    // do other stuff that needs to be done here.
    t.join(); // wait for thread to finish before returning in case thread
              // is not done
}

当我正在打字的时候,John C也加入了进来。

void methodTwo(){
    std::thread t(&ChatBubble::runChatBubbleThread, this);
    t.detach(); // let thread run to completion on it's own time
}

但是在分离时有警告。如果main在线程结束之前退出…你会有糟糕的一天。您可能希望对正在运行的线程保持标签,以确保它们在退出程序之前完成。

方法三:

void methodThree(std::vector<std::thread> & threads){
    threads.emplace_back(&ChatBubble::runChatBubbleThread, this);
}

和main

的底部
int main()
{
    std::vector<std::thread> threads;
    ...
    object.methodThree(threads);
    ...
    for (std::thread &t: threads)
    {   
        t.join();
    }
    return result;
}

随着时间的推移,编辑添加此内容将无法很好地扩展。即使线程已经停止,它们也会在vector中建立起来,因此需要不时地运行一个cleaner来检测、删除和处置已完成的线程。

编辑2:缺少&为了得到一个参考。不能复制线程有很多很好的理由。

编辑2 b。是的。这个会被挂着的线卡住。我想说,从来没有发生在我的代码,但查找几行。

通常我的线程的执行循环看起来像这样:

while (!terminated)
{
    // do stuff, but no blocking operations without a timeout.
}

如果仍然挂起,调试器就出来了。我不得不说,对于这种情况,我没有一个好的解决方案,除非在计时器上用炸弹包装循环。

线程在你构造它的时候就开始运行了。

t.join实际上等待线程t完成。它不需要等待;你不需要调用joinjoin是同步线程;有时,您希望main等待(通常,可以肯定的是,不是立即等待,而是在执行了一些您希望并行执行的其他任务之后)。当线程执行完成时,函数返回。源

另一方面,你可以使用detach,它"将对象所代表的线程与调用线程分离,允许它们彼此独立执行。"源。您应该在调用线程的析构函数之前调用detach