In this post, we will share our first impression and thoughts about developing multithreaded applications in lua.
When developing in lua you may have realized that there is no such thing as multithreading, but there is a concept that is proposed as an alternative, called coroutines, which is useful for developing single-threaded applications and sharing the processor between several routines.
Coroutines may be the desired approach for several programs, but sometimes real multithreading is required, as in the case of 2 routines that must execute simultaneously and at a different frequency or when you need a thread to block waiting for user input while doing some background processing. There are lots of examples of this, but we think we made our point.
In our case, we wanted to implement a keyboard controlled wheeled robot, so we needed 2 threads, one that would block waiting for user input (arrow keys), and another which would use the input values to control our robot.
In order to develop the keyboard controlled robot we found a multithreading library for lua called Lua Lanes (you can find more information in the LuaLanes GitHub project), which allows running multiple lua states in parallel.
Installing Lua Lanes is very easy, just run from the terminal:
|luarocks install lanes|
After installing we tried the lua scripts proposed as examples on the page, but to our surprise, they didn’t work!
We are using lua version 5.1 and Lua Lanes dated December 2010, and in my case, looking at examples and by trial and error I got to a very simple and working example, which runs 2 functions in parallel, here is the script:
This script works fine for us, it should work also for you. You could even define each loop in different lua files, decoupling the function from the threads script.
After successfully running lua lanes, the only thing left is to pass data from one lane (thread) to another. The api to do this is called Linda, which offers two ways of sending data between lanes:
There is some example using send and receive functions in the lanes documentation, and here is a working example using set and get.
Lanes and Lindas are a nice alternative to multithreading in lua, since there is no built-in functionality to do this.
It may seem not trivial to configure it at the beginning, but once you have a working example it works fine.
Last but not least, it’s not trivial to find errors on a specific lane; in case one lane stops running due to a failed assertion or some other error, that lane won’t print an error to the console and will stop running. This can be avoided by not using assert, printing errors, and exit the program in case an error is detected to signal other lanes to stop.
Are you interested in a project like this?Hire Us