我需要创建一个线程来尝试在特定时间内执行一个函数。如果线程没有成功,我需要用一个指示错误的数字来结束他。
我尝试这样做是因为我必须执行我的程序的外部库,但有时会进入无限循环以搜索尚未准备好的资源,程序中断等待该函数。
最佳答案
您无法通过将故障实现卸载到同一进程中的另一个线程来解决此问题,因为无法安全地关闭该线程,以防它运行不正常。来电 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.
您唯一的选择是:
- 向第 3 方库的供应商请求错误修复。
- 将第 3 方库卸载到它自己的进程中。在此代理过程中,您可以在自己的线程上运行第 3 方库,如果它没有及时返回(使用 WaitForSingleObject 和超时值来确定该条件),请调用 ExitProcess结束痛苦。您将必须实现 interprocess communications在您的流程之间进行操作。
关于c++ - 如何为 MFC 线程设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38374812/