c++ - 如何为 MFC 线程设置超时

标签 c++ multithreading mfc

我需要创建一个线程来尝试在特定时间内执行一个函数。如果线程没有成功,我需要用一个指示错误的数字来结束他。

我尝试这样做是因为我必须执行我的程序的外部库,但有时会进入无限循环以搜索尚未准备好的资源,程序中断等待该函数。

最佳答案

您无法通过将故障实现卸载到同一进程中的另一个线程来解决此问题,因为无法安全地关闭该线程,以防它运行不正常。来电 TerminateThread是从外面取下线的唯一方法。由于后果,当进程必须继续可靠地运行时不能使用它。

For example, TerminateThread can result in the following problems:

  • If the target thread owns a critical section, the critical section will not be released.
  • If the target thread is allocating memory from the heap, the heap lock will not be released.
  • If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
  • If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.

您唯一的选择是:

  1. 向第 3 方库的供应商请求错误修复。
  2. 将第 3 方库卸载到它自己的进程中。在此代理过程中,您可以在自己的线程上运行第 3 方库,如果它没有及时返回(使用 WaitForSingleObject 和超时值来确定该条件),请调用 ExitProcess结束痛苦。您将必须实现 interprocess communications在您的流程之间进行操作。

关于c++ - 如何为 MFC 线程设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38374812/

相关文章:

c++ - 为什么我无法在CListBox 中获取选中的项目?多功能 Controller

c++ - 如何更改工具栏中 QAction 的颜色?

c++ - 如何防止 libwebsockets 客户端超时

multithreading - clojure 是 "multithread"吗?

c - Posix Pthread 互斥

c++ - CSocket 在发送时不阻塞

c++ - MFC画圆

c++ - 堆栈限制和线程之间的关系

c++ - 如何使用 optarg 获取多个值?

c++ - 在线程之间发送字符串数据 (Win32)