Hi, so I’ve been wanting to dig deeper into this so I can really understand what a thread is.
Let’s look at an example:
function x()
print('yoyo')
spawn(function()
wait(999) --//not that i'd use this for anything other than the example.
print('blah')
end)
print('not affected by that yield o_o')
end
What I’ve always thought happens here, is that spawn creates a new ‘thread’ of execution that runs separate from the core thread that’s calling f() .
Not sure what truly is going on in this example, but please correct me as needed, this might not be super useful information but I’ve been intrigued lately to get a better understanding. Thanks.
A thread, in non computer scientific terms, is what you could call a task. Multi-tasking is similar to having multiple threads: they run simultaneously or in other words multi threaded. Roblox’s Task Scheduler system is essentially multiple threads being handled. This should probably help you understand what a thread, or “threading” is.
Roblox does not currently support hardware multithreading for Lua. What your code basically does is it queues a function to execute, then keeps going. When the queue reaches that function, it runs, hits wait(999), and re-queues itself until at least 999 seconds have elapsed. Nothing here is actually run in parallel.
Technically, the time between spawn and print('not affected by that yield') is the time where borh threads are running simultaneously. Granted, this is indeed a very very short time, it does not change the fact a second thread is made. A better example would have been:
function x()
print('yoyo')
spawn(function()
wait(999) --//not that i'd use this for anything other than the example.
print('blah')
end)
print('not affected by that yield o_o')
wait(2)
print('another print that is not affected by that yield')
end
There’s not really anything happening “simultaneously”, at least with how Roblox currently works. A new Lua thread (read: queued code) is created and pushed onto the thread scheduler. The actual execution runs in a single hardware thread.
Random question that I think relates to this topic, but does that mean everything will be put on a singular CPU thread as well, because in reality there’s only one actual thread running at a time, since Roblox is single-threaded?
Yes, hardware-wise there are no new threads, but spawn does create a new lua thread and runs it simultaneously, similar to coroutine.wrap it does not yield until the current task is completed.
@C_Sharper I’m not sure about the rest of the engine, but I do know right now that all Lua code runs on the same thread.
@DevBuckette I’m not sure what you mean exactly. I think it’s misleading to say “Lua thread” and say things are happening simultaneously. Lua “threads” don’t run simultaneously, they run in order on a queue.