c++新线程休眠主线程
C++ new thread sleeps main thread
运行以下代码:
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完成。它不需要等待;你不需要调用join
。join
是同步线程;有时,您希望main等待(通常,可以肯定的是,不是立即等待,而是在执行了一些您希望并行执行的其他任务之后)。当线程执行完成时,函数返回。源
另一方面,你可以使用detach
,它"将对象所代表的线程与调用线程分离,允许它们彼此独立执行。"源。您应该在调用线程的析构函数之前调用detach
。
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 工作线程在执行太快后永久休眠
- 睡眠线程或进程的指令是否在线程/进程休眠时继续执行?
- 提升:两个工作线程,使主线程休眠,直到它们都完成
- 休眠 X 毫秒或线程信号
- 构造函数内的休眠线程和线程初始化
- 让一个boost线程休眠几纳秒
- Windows线程从另一个线程休眠和唤醒
- 如何休眠APR线程