c - interrupt a function call which is executing in a thread

巧了我就是萌 提交于 2019-12-05 02:16:51

问题


I have a DLL which contains a thread function whose pseudocode looks like:

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();
}

And in the code which uses this DLL, the cleanup function looks like:

void cleanup()
{
    StopEverything();

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

My question is twofold:

  1. Is there a better way to stop my workerThreadFunc() from executing instead of doing checks like that at various checkpoints?
  2. Suppose workerThreadFunc() is stuck inside doLaboriousTask2() when the main application calls StopEverything(). Is there a way to interrupt doLaboriousTask2() and have it exit immediately?

Thanks!


回答1:


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

Probably not. There's no fully reliable way to pre-emptively halt a thread in unmanaged code. Anything that purports to do that leads to TerminateThread. And the documentation lists all sorts of dire consequences for using that function. For example:

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

You ask:

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

Well, you could call TerminateThread but, for all the reasons described in the documentation, you almost certainly should not do that.



来源:https://stackoverflow.com/questions/15544255/c-interrupt-a-function-call-which-is-executing-in-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!