user8201141
user8201141

Reputation:

Lua - how to simulate "multithreading"?

I have 2 functions:

function func1()
   while true do
       -- listen on connection
   end
end

function func2()
   while true do
       -- execute other code
   end
end

I want to run both functions "simultaneously" while sharing variables between them. I have tried to create a dispatcher that makes a coroutine with the two functions but I can't think of a way to schedule them to quickly alternate their execution. (func1 runs for a second, func2 runs for a second, func1 runs for a second, and so on)

Upvotes: 2

Views: 3560

Answers (2)

Henri Menke
Henri Menke

Reputation: 10939

There exist C libraries for Lua which expose methods for multithreading or multiprocessing. Some examples would be

All of these are third-party solution and, as the other answer explains, there are no built-in capabilities for asynchronous multithreading in Lua.

I think lua-llthread would come closest to what you describe. It supports communication between threads via ZeroMQ.

Upvotes: 0

Nicol Bolas
Nicol Bolas

Reputation: 473312

Lua does not support asynchronous multithreading. It only supports cooperative threading. That means the two "threads" have to be designed to give the other thread time to execute. Such designs are usually highly dependent on what you're trying to accomplish.

Your example talks about one thread listening for a connection and the other thread doing something (either with data from that connection or not; it's not exactly clear). In such a system, it would be a good idea to have func1 invoke the thread for func2 when the connection hasn't provided new data. And func2 would return control back to func1 only when it has finished processing something.

But there is no one-size-fits-all solution to cooperative multithreading.

Upvotes: 3

Related Questions