Francis
Francis

Reputation: 757

Is lua table thread safe?

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?

Upvotes: 3

Views: 3357

Answers (3)

Francis
Francis

Reputation: 757

NO, lua table is not thread safe.

And yes, all operation on table t will need lua_lock, because none of them is atomic operation.

Upvotes: 0

Deduplicator
Deduplicator

Reputation: 45654

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

Upvotes: 3

Mead
Mead

Reputation: 100

lua table isn't thread safe, but there's no need to lock since threads don't read/write on the same element.

Upvotes: 0

Related Questions