c - 如何向正在进行长时间操作的线程发送消息?

标签 c multithreading winapi

我有一个主线程和一个工作线程。当主线程即将终止时,我需要向工作线程发送一条消息,以便它可以干净地终止自身(我听说 TerminateThread() 是一个坏主意)。

工作线程将执行一个冗长的操作(将花费超过 30 秒),因此有没有办法在执行此冗长操作的同时向其发送消息。或者也许我的程序设计是错误的,工作线程不应该执行如此长度的操作?

最佳答案

作为一般原则,不要终止线程。

您的后台工作线程可以定期检查程序是否要退出。您应该使用std::atomic<bool>要做到这一点。这是有关如何使用它的示例。

#include <iostream>
#include <thread>
#include <atomic>

volatile std::atomic<bool> g_bExit(false);

void thread1()
{
   while( !g_bExit )
   {
      // do stuff here
   }
}

int main()
{
      std::thread th1(thread1);

      g_bExit = true;

      th1.join() ; // wait for thread
}

关于c - 如何向正在进行长时间操作的线程发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29651507/

相关文章:

c - 上采样的正确方法是什么?

delphi - 关闭应用实例但不关闭当前实例

c++ - 将Qt集成到现有VS项目中以替换WinAPI

windows - 所有版本的 Windows 上的 Win32 透明控件

c - C中的条件语句和控制语句有什么区别吗?

c - 什么是 c 中的错误文件描述符?

c - 使用 typedef 结构时出现错误 'a value of type "X *"cannot be assigned to an entity of type "X *"'

java - 在Java中,我可以依靠引用分配是原子的来实现写时复制吗?

python - Selenium 线程 : how to run multi-threaded browser with proxy ( python)

c# - 解释代码: c# locking feature and threads