35
votes

Coding in Lua, I have a triply nested loop that goes through 6000 iterations. All 6000 iterations are independent and can easily be parallelized. What threads package for Lua compiles out of the box and gets decent parallel speedups on four or more cores?

Here's what I know so far:

  • luaproc comes from the core Lua team, but the software bundle on luaforge is old, and the mailing list has reports of it segfaulting. Also, it's not obvious to me how to use the scalar message-passing model to get results ultimately into a parent thread.

  • Lua Lanes makes interesting claims but seems to be a heavyweight, complex solution. Many messages on the mailing list report trouble getting Lua Lanes to build or work for them. I myself have had trouble getting the underlying "Lua rocks" distribution mechanism to work for me.

  • LuaThread requires explicit locking and requires that communication between threads be mediated by global variables that are protected by locks. I could imagine worse, but I'd be happier with a higher level of abstraction.

  • Concurrent Lua provides an attractive message-passing model similar to Erlang, but it says that processes do not share memory. It is not clear whether spawn actually works with any Lua function or whether there are restrictions.

  • Russ Cox proposed an occasional threading model that works only for C threads. Not useful for me.

I will upvote all answers that report on actual experience with these or any other multithreading package, or any answer that provides new information.


For reference, here is the loop I would like to parallelize:

for tid, tests in pairs(tests) do
  local results = { }
  matrix[tid] = results
  for i, test in pairs(tests) do
    if test.valid then
      results[i] = { }
      local results = results[i]
      for sid, bin in pairs(binaries) do
        local outcome, witness = run_test(test, bin)
        results[sid] = { outcome = outcome, witness = witness }
      end
    end
  end
end

The run_test function is passed in as an argument, so a package can be useful to me only if it can run arbitrary functions in parallel. My goal is enough parallelism to get 100% CPU utilization on 6 to 8 cores.

6
I think that most of packages you've listed are concurrent programming ones, not specifically multithreaded. I suggest changing a title (as multithreading in Lua is a red flag for some of us).Alexander Gladysh
May be also worth listing: luaforge.net/projects/alua (though seems outdated)Alexander Gladysh
@DeadMG: Over my dead body. My host language is C, and its threading constructs are no better than Lua's. Why would I want to bother with a lower-level language? I suspect I'll be using POSIX threads and POSIX message queues, but in Lua.Norman Ramsey

6 Answers

2
votes

Norman wrote concerning luaproc:

"it's not obvious to me how to use the scalar message-passing model to get results ultimately into a parent thread"

I had the same problem with a use case I was dealing with. I liked lua proc due to its simple and light implementation, but my use case had C code that was calling lua, which was triggering a co-routine that needed to send/receive messages to interact with other luaproc threads.

To achieve my desired functionality I had to add features to luaproc to allow sending and receiving messages from the parent thread or any other thread not running from the luaproc scheduler. Additionally, my changes allow using luaproc send/receive from coroutines created from luaproc.newproc() created lua states.

I added an additional luaproc.addproc() function to the api which is to be called from any lua state running from a context not controlled by the luaproc scheduler in order to set itself up with luaproc for sending/receiving messages.

I am considering posting the source as a new github project or contacting the developers and seeing if they would like to pull my additions. Suggestions as to how I should make it available to others are welcome.

2
votes

Check the threads library in torch family. It implements a thread pool model: a few true threads (pthread in linux and windows thread in win32) are created first. Each thread has a lua_State object and a blocking job queue that admits jobs added from the main thread.

Lua objects are copied over from main thread to the job thread. However C objects such as Torch tensors or tds data structures can be passed to job threads via pointers -- this is how limited shared memory is achieved.

1
votes

This is a perfect example of MapReduce

You can use LuaRings to accomplish your parallelization needs.

1
votes

Concurrent Lua might seem like the way to go, but as I note in my updates below, it doesn't run things in parallel. The approach I tried was to spawn several processes that execute pickled closures received through the message queue.

Update

Concurrent Lua seems to handle first-class functions and closures without a hitch. See the following example program.

require 'concurrent'

local NUM_WORKERS = 4       -- number of worker threads to use
local NUM_WORKITEMS = 100   -- number of work items for processing

-- calls the received function in the local thread context
function worker(pid)
    while true do
        -- request new work
        concurrent.send(pid, { pid = concurrent.self() })
        local msg = concurrent.receive()

        -- exit when instructed
        if msg.exit then return end

        -- otherwise, run the provided function
        msg.work()
    end
end

-- creates workers, produces all the work and performs shutdown
function tasker()
    local pid = concurrent.self()

    -- create the worker threads
    for i = 1, NUM_WORKERS do concurrent.spawn(worker, pid) end

    -- provide work to threads as requests are received
    for i = 1, NUM_WORKITEMS do
        local msg = concurrent.receive()

        -- send the work as a closure
        concurrent.send(msg.pid, { work = function() print(i) end, pid = pid })
    end

    -- shutdown the threads as they complete
    for i = 1, NUM_WORKERS do
        local msg = concurrent.receive()
        concurrent.send(msg.pid, { exit = true })
    end
end

-- create the task process
local pid = concurrent.spawn(tasker)

-- run the event loop until all threads terminate
concurrent.loop()

Update 2

Scratch all of that stuff above. Something didn't look right when I was testing this. It turns out that Concurrent Lua isn't concurrent at all. The "processes" are implemented with coroutines and all run cooperatively in the same thread context. That's what we get for not reading carefully!

So, at least I eliminated one of the options I guess. :(

1
votes

I realize that this is not a works-out-of-the-box solution, but, maybe go old-school and play with forks? (Assuming you're on a POSIX system.)

What I would have done:

  • Right before your loop, put all tests in a queue, accessible between processes. (A file, a Redis LIST or anything else you like most.)

  • Also before the loop, spawn several forks with lua-posix (same as the number of cores or even more depending on the nature of tests). In parent fork wait until all children will quit.

  • In each fork in a loop, get a test from the queue, execute it, put results somewhere. (To a file, to a Redis LIST, anywhere else you like.) If there are no more tests in queue, quit.

  • In the parent fetch and process all test results as you do now.

This assumes that test parameters and results are serializable. But even if they are not, I think that it should be rather easy to cheat around that.

1
votes

I've now built a parallel application using luaproc. Here are some misconceptions that kept me from adopting it sooner, and how to work around them.

  • Once the parallel threads are launched, as far as I can tell there is no way for them to communicate back to the parent. This property was the big block for me. Eventually I realized the way forward: when it's done forking threads, the parent stops and waits. The job that would have been done by the parent should instead be done by a child thread, which should be dedicated to that job. Not a great model, but it works.

  • Communication between parent and children is very limited. The parent can communicate only scalar values: strings, Booleans, and numbers. If the parent wants to communicate more complex values, like tables and functions, it must code them as strings. Such coding can take place inline in the program, or (especially) functions can be parked into the filesystem and loaded into the child using require.

  • The children inherit nothing of the parent's environment. In particular, they don't inherit package.path or package.cpath. I had to work around this by the way I wrote the code for the children.

  • The most convenient way to communicate from parent to child is to define the child as a function, and to have the child capture parental information in its free variables, known in Lua parlances as "upvalues." These free variables may not be global variables, and they must be scalars. Still, it's a decent model. Here's an example:

    local function spawner(N, workers)
      return function()
        local luaproc = require 'luaproc'
        for i = 1, N do
          luaproc.send('source', i)
        end
        for i = 1, workers do
          luaproc.send('source', nil)
        end
      end
    end
    

    This code is used as, e.g.,

    assert(luaproc.newproc(spawner(randoms, workers)))
    

    This call is how values randoms and workers are communicated from parent to child.

    The assertion is essential here, as if you forget the rules and accidentally capture a table or a local function, luaproc.newproc will fail.

Once I understood these properties, luaproc did indeed work "out of the box", when downloaded from askyrme on github.

ETA: There is an annoying limitation: in some circumstances, calling fread() in one thread can prevent other threads from being scheduled. In particular, if I run the sequence

local file = io.popen(command, 'r')
local result = file:read '*a'
file:close()
return result

the read operation blocks all other threads. I don't know why this is---I assume it is some nonsense going on within glibc. The workaround I used was to call directly to read(2), which required a little glue code, but this works properly with io.popen and file:close().

There's one other limitation worth noting:

  • Unlike Tony Hoare's original conception of communicating sequential processing, and unlike most mature, serious implementations of synchronous message passing, luaproc does not allow a receiver to block on multiple channels simultaneously. This limitation is serious, and it rules out many of the design patterns that synchronous message-passing is good at, but it's still find for many simple models of parallelism, especially the "parbegin" sort that I needed to solve for my original problem.