Page 1 of 1

Lua - Creating multi-threaded scripts.

Posted: Thu Jan 15, 2009 12:47 am
by zer0
Hey all,

Wondering how to do multi-threaded scripts, I'm pretty sure it involves the use of co-routines but I don't entirely understand the documentation.
http://lua-users.org/wiki/CoroutinesTutorial

So just to give you a quick example, if I had the following:

Code: Select all

function foo()
  for i=1, 10 do
    print("i=", i)
  end
end

foo()
print("in-between")
I want the output to be somewhere along the lines of:

Code: Select all

i=1
in-between
i=2
...
i=10
note - the "in-between" should be anywhere since my requirements are that it continues executing and does the foo function is a separate thread.

How would I do the above code to make it multi-threaded?
I tried doing this code:

Code: Select all

co = coroutine.create(function ()
       for i=1,10 do
         print("i", i)
         --coroutine.yield()
       end
     end)
     
coroutine.resume(co)
print("in-between")
But the "in-between" showed at the end, which suggests it's still single threaded, am I wrong?

Re: Lua - Creating multi-threaded scripts.

Posted: Thu Jan 15, 2009 4:13 am
by Administrator
Both parts need to be coroutines. That is, the print statement needs to be in a separate coroutine. Then you would need to resume other threads within each other. Try maybe something like this:

Code: Select all

local threads = {};

function createThread(func)
  local tmp = coroutine.create(func);
  table.insert(threads, tmp);
end


function main()
  local func1 = function()
    while(true) do
      for i = 1,10 do
        print(i);
        coroutine.yield();
      end
    end
  end

  local func2 = function ()
    while(true) do
      print("Hello World");
      coroutine.yield();
    end
  end

  createThread(func1);
  createThread(func2);

  while(true) do
    for i,v in pairs(threads) do
      coroutine.resume(v);
    end
  end
end
startMacro(main);
Also remember that once the function returns that thread is "dead". That's why I wrapped both functions in while loops for this example.

Re: Lua - Creating multi-threaded scripts.

Posted: Thu Jan 15, 2009 6:56 am
by zer0
Oh bugger looks like it's more complicated than I thought. :o

Give me awhile to digest all this. ;)

Thanks as always Elv.