4

Hi Everybody,

I have a third party library that contains an error. When I call a function it may hang. The library function is called inside a dll. I decided to move the call into the thread and wait for some time. If thread is finished then OK. If not – I should terminate it compulsory.

The simplified example here:

unsigned Counter = 0;
void f()
{
    HANDLE hThread;
    unsigned threadID;

    // Create the second thread.
    hThread = (HANDLE)_beginthreadex( NULL, 0, DoSomething, NULL, 0, &threadID );

    if (WAIT_TIMEOUT == WaitForSingleObject( hThread, 5000 ))
    {
        TerminateThread(hThread, 1);    
        wcout << L"Process is Timed Out";
    }
    else
    {
        wcout << L"Process is Ended OK";
    }

    CloseHandle(hThread);   

    wcout << Counter;
}

unsigned int _stdcall DoSomething( void * /*dummy*/ )
{
    while (1)
    {

        ++Counter;

    }
    _endthreadex( 0 );
    return 0;
}

The Question

  1. The TerminateThread() function is not recommended to call.
  2. As I mentioned before, the thread is running inside a dll. If I terminate the thread using TerminateThread() my dll would not unload using FreeLibrary() or even FreeLibraryAndExitThread(). Both functions hangs.

How to Terminate the thread and keep FreeLibrary() working?

Thanks.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
Mar
  • 941
  • 1
  • 10
  • 18
  • 2
    perhaps you should look at hosting the rouge dll in a separate process and just killing the process if stuff goes pear shape? – Sam Saffron Jun 17 '09 at 01:32

1 Answers1

14

Unfortunately, you can't arbitrarily terminate a thread safely.

TerminateThread causes the thread to terminate immediately, even if the thread is holding locks or modifying some internal state. TerminateThread can cause random hangs in your application (if the thread was holding a lock) or a crash (if the thread were modifying some state and it is left inconsistent)

If you cannot trust the DLL to behave correctly and this is causing significant reliability issues for you, you should move the code invoking the DLL into a separate process - terminating a process is much safer.

Michael
  • 54,279
  • 5
  • 125
  • 144
  • Good insights on the pitfalls of terminating a thread abruptly. – nsantorello Jun 17 '09 at 01:55
  • Thanks, I will try to expriment on your advice. – Mar Jun 17 '09 at 02:05
  • I wish I could upvote this twice after dealing with production systems that are the result of people thinking the thread could be terminated. – Adam Mitz Jun 17 '09 at 03:39
  • Even if Windows does release any resource that the thread might have a hold of in the midst its shocking death, there could still be `application-level` inconsistencies that it will cause... – daparic Nov 22 '18 at 03:28