Lua使用线程同时运行对象

时间:2015-01-05 16:55:44

标签: multithreading object concurrency lua

我需要让对象函数与其他对象同时运行,例如。 objA必须与objB等同时运行。我编写了简单的代码(见下文),我的问题是如何让线程中的myOBJ_A:doSomething()工作?

local llthreads = require"llthreads2"
oo = require "loop.base"

OBJ_A = oo.class {
  obj_A_value = 0,
}
function OBJ_A:doSomething()
    print(self)
end

myOBJ_A = OBJ_A {
    obj_A_value=240,
}
print(myOBJ_A) --eg. this table is table: 0081BC78
thread = llthreads.new([[
print(myOBJ_A) --that prints nil no idea why
    myOBJ_A:doSomething() --this wont't work because above table id has changed/disappeared
    ]], myOBJ_A)

assert(thread:start())

我从上面的代码中收到错误消息:

nil
Error from thread: [string " ..."]:3: attempt to index global 'myOBJ_A' (a nil value)
stack traceback:
        [string " ..."]:3: in main chunk

1 个答案:

答案 0 :(得分:0)

每个线程都有自己的Lua State。您可以在构造函数中传递值的副本,但不能使用来自父Lua State的upvalues,也不能复制fnctions和fulluserdata。您也可以使用sring.dump来简化代码。

local llthreads = require"llthreads2"
local F = string.dump

-- you can copy table to thread
local value = { obj_A_value = 240 }

local thread = llthreads.new(F(function(A_value)
  local oo = require "loop.base"

  local OBJ_A = oo.class { obj_A_value = 0 }

  function OBJ_A:doSomething()
    print(self)
  end

  local myOBJ_A = OBJ_A(A_value)

   myOBJ_A:doSomething()
end), value)

assert(thread:start())

此外,您可以在单独的模块中移动类的实现,并在多个线程中使用它,但是您不能在多个线程中使用相同的对象。