Error. Assertion failed: ThreadID == FPlatformTLS::GetCurrentThreadId()

I need to create threads in cycle and when new thread is reaching some place of main thread code - it should be killed and memory should be freed. I’m using this to create threads in cycle.

 //runner object
 void ThreadRider::CallThread(APlayer* Caller, MMessage *Msg, float TimeDelay)
 {
     MessageToSend = Msg;
     TimeToWait = TimeDelay;
     CallingActor = Caller;
     Thread = FRunnableThread::Create(this, TEXT("MessageThreadWorker"), 0, TPri_Normal);
 }

To check stability I’m simply creating and Kill(true) 'ing thread in Tick() of actor which owns runner object.
After of 2-3 minutes of running tick() which is

	MessageDelayThread->Thread->Kill(true);
	MessageDelayThread->Thread = NULL;
	MessageDelayThread->CallThread(this, Message, NextEventTime);

UE is throwing an exception at FRunnableThread::FreeTls().
More exactly - Assertion failed: ThreadID == FPlatformTLS::GetCurrentThreadId()

Why is that happening? I thought Kill(true) waits for stuff to complete so this error should not happen?

Hi Unteroid,

It sounds like you’re calling Kill from a thread different to the one which the thread was originally created from. Only the ‘creating thread’ can be responsible for killing it too.

Andrew

I’ve changed few things to

//inside runner object
    void ThreadRider::Shutdown()
    {
    	Thread->Kill(true);
    	Thread = NULL;
    }
    
    //inside tick
    MessageDelayThread->Shutdown();
    MessageDelayThread->CallThread(this, Message, NextEventTime);

And still having same issue after 5 minutes of run

I’ve figured out this thing is happening when I’m leaving game to tick and fold it to do some other PC job.
I can halt thread creation / tick on game fold, but I’m still interested in what can cause this problem?