Celtoys / Remotery

Single C file, Realtime CPU/GPU Profiler with Remote Web Viewer
Apache License 2.0
3.11k stars 264 forks source link

Crash when quickly shutting down remotery #214

Closed JCash closed 2 years ago

JCash commented 2 years ago

In my use case I have a unit test that should fail fast. When doing so, it creates a Remotery instance at startup, and then quickly proceeds to shutting down, and subsequently destroying the Remotery instance.

However, it seems there is a gap in the sequence of the startup process which isn't completely protected against this behavior.

The GatherThreads gets created just before the loop in the SampleThreads thread. So, it becomes a rogue thread which will then 100% crash in the ThreadProfilers_GetThreadProfiler since the mutex is destroyed (mtxLock(&thread_profilers->threadProfilerMutex);).

I have a repro test case here. I compile with

cl /D_DEBUG /Od /DEBUG /Zi -Ilib sample/crash.c lib/Remotery.c /link /out:build\crash.exe

The output from it shows the problem. In loop 1, the

0: Create instance
   created thread: 00891A70
   created thread: 00891D70
Remotery_Destructor begin!
    Thread 00891D70 joined!
   created thread: 00891CB0
SampleThreadsLoop: started gather threads.
    Thread 00891A70 joined!
Remotery_Destructor done!
0: Destroyed instance
1: Create instance
   created thread: 00891B30
   created thread: 00891E10
Remotery_Destructor begin!
    Thread 00891E10 joined!
   created thread: 00891E10                                 <- Creating a new thread while the Remotery destructor has started
SampleThreadsLoop: started gather threads.
    Thread 00891B30 joined!
Remotery_Destructor done!
1: Destroyed instance
2: Create instance
   created thread: 00891DF0
   created thread: 00891E30
Remotery_Destructor begin!
    Thread 00891E30 joined!

<crash, the thread 00891E10 is still trying to do work>

As a workaround, for now I can remove the usage of the profiling library for these unit tests.