PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Threading Code

Threading Code

Jul 03 2018, 11:24 AM PST 2 min

Threading is a tool that allows two or more pieces of code to run at once. You cannot expect two while loops (as shown below) to run simultaneously in the same thread. A naive attempt at this shown below, fails

while true do 
	wait() 
	print("Hello World!") 
end

while true do 
	wait() 
	print("Goodbye World!") 
end

Since lines of code are run in sequentially, and the first loop never stops, the second loop never gets executed

Constructing a thread

There is a specific function, spawn, which can be used to start a function in a new thread:

Of course, at the moment the thread isn’t getting us anything we didn’t already get with the while loop

Running code simultaneously

We can now use this code to solve our original problem of running two pieces of code in parallel:

For symmetry, we could put the goodbye code in a thread too:

function helloThread()
	while true do
		print("Hello World!")
		wait()
	end
end

function goodbyeThread()
	while true do
		print("Hello World!")
		wait()
	end
end

-- start both threads in parallel
spawn(helloThread)
spawn(goodbyeThread)

Information to consider

Using spawn creates a new thread. Having many threads will eventually cause lag in a game, so it is best to try and keep the thread count to a minimum by optimizing code and combining all that can be mixed.

Another important fact to remember is that just like functions, threads take on the environment of their parent context of where they were created. So any existing variables of its parent stack, local or global, will fall into the newly created coroutine’s envionrment as well.

See Also

  • Articles/Thread scheduler
  • Articles/Beginners Guide to Coroutines
Tags:
  • optimization
  • coding
  • lua
  • concept