A coroutine / thread closing itself

I am trying to have a coroutine to close itself:

local someCoroutine

local function stuff()
	for i = 1,5 do
		print(i)
		task.wait(0.1)
	end
end

local function cleanup()
	coroutine.close(someCoroutine) -- errors "cannot close running coroutine"
	-- do some cleanup stuff
end

someCoroutine = coroutine.create(function()
	stuff()
	cleanup()
end)

coroutine.resume(someCoroutine)

What I am trying to achieve is create a thread that runs a function. After the function terminates, it does a cleanup, which essentially closes the thread as well.

Apparently that is not possible when cleanup() and stuff() is under the same thread. Since a thread is considered running when running cleanup() and running threads can not be closed (why?).

If I add put coroutine.close under another thread, AND a task.wait(), it has no errors, which is quite a “hacky” fix.

local function cleanup()
	coroutine.wrap(function()
		task.wait() -- without this it errors "cannot close NORMAL coroutine"
		coroutine.close(someCoroutine)
	end)()
end

Is there any workaround without this “hacky” fix? In my case, there might be situations where I have to assure that the thread is completely closed before continunning.

1 Like

You can use the task library

local thread
thread = task.spawn(function()
task.cancel(thread)
end)
local thread
thread = task.spawn(function()
     task.wait(1) task.cancel(thread)
end)

Task library straight up tells you “cannot cancel thread”

image

Hmm, if you don’t mind me asking, why do you need to close the thread? It closes by itself once the loop is finished I’m pretty sure.

Do it like this so it suspends the thread before cancelling it.

local thread = coroutine.running()
task.defer(task.cancel, thread)
coroutine.yield()

If it’s a different thread, you can double check the status of the thread as well, making sure it’s suspended. coroutine.status(thread)

2 Likes

I think just using return would just end the function and close itself.

Nevermind, I think you are right. I need to close the thread because in my code, cleanup() can be called from elsewhere to stop the thread. Guess I will just have to check whether the thread is not running when closing it.

1 Like