How do you cancel the current running thread?

Hi,

So in my signal implementation I have run into an issue with the :Wait method. If the signal is dead, and after its death its :Wait method is called, I want it to just close the running thread. Should I yield the thread infinitely, I will have a memory leak because the thread is in a suspended state, so it is expected to resume at some point. What I want is to kill the thread in which the signal:Wait method is called.

I’ve tried using task.cancel and coroutine.close on coroutine.running(), however in both cases it produces an error.

Using task lib gives me cannot cancel thread
Using coroutine lib gives me cannot close running coroutine

Any ideas as to how I’d approach it?

Here’s what I have currently:

function signal:Wait()
	assert(self.IsSignal, 'Attempt to call member function Signal.Wait on a non-signal value!')
	
	if self._dead then
		task.cancel(coroutine.running())
	end
	
	table.insert(self._yields, coroutine.running())
	return coroutine.yield()
end

Currently I’m thinking of making a boilerplate solution by deferring a task.cancel call on the active thread, then yielding the active thread but I really don’t know if this is the right way to go about doing this (ie. task.defer(task.cancel, coroutine.running()); coroutine.yield())

Thanks for any insight and help.

You used a lot of vocabulary I didn’t understand BUT :

I found a post that says the garbage collector will take care of the generated leak, assuming there’s no reference to the yielded thread. I’m unsure as to how accurate this information is so I would recommend testing it and marking your own solution.

2 Likes

This seems to be the case actually, I tried this:

task.spawn(function() 
    while true do 
        task.spawn(function()
            coroutine.yield() 
        end) 
        task.wait() 
    end 
end) 
while true do 
    print(gcinfo()) 
    task.wait() 
end

You will notice the number does increase but goes back down after a certain point, in my case around 32000.

Thanks! I thought the memory would just indefinitely increase.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.