相关文章推荐
冷静的树叶  ·  TypeScript ...·  1 年前    · 
另类的墨镜  ·  Matlab中错误使用 bsxfun ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Say, I have a lua table t={"a"={}, "b"={}} .

My question is, I have two threads, thread A, thread B. And if I create two lua_State individually for these two threads through lua_newthread, and thread A only read/write t.a , thread B only read/write t.b .

Should I use lua_lock in each thread above?

If the answer is YES, then, does any of operation on t need a lua_lock?

TL;DR: A Lua engine-state is not thread-safe, so there's no reason to make the Lua table thread-safe.

A lua_State is not the engine state, though it references it. Instead, it is the state of a Lua thread, which is no relation to an application thread. Lua threads with the same engine state cannot execute concurrently, as the Lua engine is inherently single-threaded (you may use an arbitrary number of engines at the same time though), instead they are cooperatively multitasked.

So lua_State *lua_newthread (lua_State *L); creates a new Lua thread, not an OS thread.

lua_lock and the like do not refer to thread safety, but were the way native code can keep hold of Lua objects across calls into the engine in version 2 of the implementation: https://www.lua.org/manual/2.1/subsection3_5_6.html
The modern way is using the registry, a Lua table accessible from native code: http://www.lua.org/manual/5.3/manual.html#4.5

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question . Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers .