如何设置MFC线程的超时(How to set a timeout to a MFC Thread)

编程入门 行业动态 更新时间:2024-10-28 06:31:51
如何设置MFC线程的超时(How to set a timeout to a MFC Thread)

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

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

I need to create a thread that tries to execute a function in a specific amount of time. If the thread did not get success, I need to finish him with a number that indicates an error.

I am trying to do this because of a external library of my program that I have to execute, but sometimes enter in an infinity loop in a search of a resource that is not ready yet and the program break waiting for that function.

最满意答案

你不能通过将错误的实现卸载到同一进程中的另一个线程来解决这个问题,因为如果它运行不正常,就无法安全地关闭该线程。 调用TerminateThread是从外部取下线程的唯一方法。 由于后果,当进程必须继续可靠地运行时,不能使用它。

例如, TerminateThread可能会导致以下问题:

如果目标线程拥有临界区,则不会释放临界区。 如果目标线程正在从堆中分配内存,则不会释放堆锁。 如果目标线程在终止时正在执行某些kernel32调用,则线程进程的kernel32状态可能不一致。 如果目标线程正在操纵共享DLL的全局状态,则DLL的状态可能会被破坏,从而影响DLL的其他用户。

您唯一的选择是:

从第三方库的供应商处请求错误修复。 将第三方库卸载到自己的进程中。 在此代理进程中,您可以在其自己的线程上运行第三方库,如果它没有及时返回(使用具有超时值的WaitForSingleObject来确定该条件),请调用ExitProcess以结束痛苦。 您必须在流程之间实现进程间通信才能使其正常工作。

You cannot solve this by offloading the faulting implementation onto another thread in the same process, because there is no way to safely shut down that thread, in case it runs afoul. Calling TerminateThread is the only way to take down a thread from the outside. Due to the consequences, it cannot be used when a process must continue to run reliably.

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.

Your only options are:

Request a bugfix from the vendor of the 3rd party library. Offload the 3rd party library into its own process. In this surrogate process you can run the 3rd party library on its own thread, and if it doesn't return in time (use WaitForSingleObject with a timeout value to determine that condition), call ExitProcess to end the misery. You will have to implement interprocess communications between your processes for this to work.

更多推荐

本文发布于:2023-07-22 18:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222266.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   如何设置   MFC   Thread   set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!