gpt4 book ai didi

c - 中断正在线程中执行的函数调用

转载 作者:可可西里 更新时间:2023-11-01 09:29:56 24 4
gpt4 key购买 nike

我有一个 DLL,其中包含一个线程函数,其伪代码如下所示:

volatile BOOL stopped = FALSE;

void StopEverything()
{
/* Enter critical section */
stopped = TRUE;
/* Leave critical section */
}

void workerThreadFunc()
{
Initialize();

/* Checkpoint 1 */
if(stopped)
{
/* Do cleanup */
return;
}

doLaboriousTask1();

/* Checkpoint 2 */
if(stopped)
{
/* Do cleanup */
return;
}

doLaboriousTask2();

Uninitialize();
}

在使用这个 DLL 的代码中,清理函数如下所示:

void cleanup()
{
StopEverything();

/* Wait for all threads to exit */
/* Do other cleanup */
}

我的问题有两个:

  1. 有没有更好的方法来阻止我的 workerThreadFunc() 执行而不是像在各个检查点那样进行检查?
  2. 假设当主应用程序调用 StopEverything() 时,workerThreadFunc() 卡在 doLaboriousTask2() 中。有没有办法中断 doLaboriousTask2() 并让它立即退出?

谢谢!

最佳答案

Is there a better way to stop my workerThreadFunc() from executing instead of doing checks like that at various checkpoints?

可能不会。没有完全可靠的方法可以先发制人地停止非托管代码中的线程。任何声称这样做都会导致 TerminateThread .文档列出了使用该功能的各种可怕后果。例如:

  • 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.

你问:

Is there a way to interrupt doLaboriousTask2() and have it exit immediately?

好吧,您可以调用 TerminateThread,但是由于文档中描述的所有原因,您几乎肯定不应该这样做。

关于c - 中断正在线程中执行的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15544255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com