TIL: Multithreading in Lua

Tom Deneire
2 min readDec 8, 2023
Photo by Andrés Gómez on Unsplash

Concurrency in Lua

Today I was solving day 5, part 2 of Advent of Code 2023:

which I hoped to optimize using concurrency (as it involves millions of computations).

As I’m doing these puzzles in Lua this year, I first looked at Lua coroutines, but these alone are not enough to achieve true concurrency in the sense of multithreading (using a single CPU) or parallelism (using multiple CPUs).

Luv

There is, however, a project luvthat offers bindings of libuv (a multi-platform support library for asynchronous I/O, primarily developed for Node.js) for LuaJIT:

It comes with extensive documentation and a folder of examples:

You install luv with luarocks

luarocks install luv

Multithreading example

I don’t think you can achieve true, multi-CPU, parallelism with luv , but it is possible to do multithreading.

I’m recording an example for future reference here:

local luv = require('luv')

-- Define a function that executes a time-consuming task
function doTask(i)
longTask = function(i)
print("Starting task " .. i .. "...")…

--

--