SBKarr
SBKarr

Reputation: 548

Lua operations, that works in mutitheaded environment

My application uses Lua in multithreaded environment with global mutex. It implemented like this:

  1. Thread locks mutex,
  2. Call lua_newthread
  3. Perform some initialization on coroutine
  4. Run lua_resume on coroutine
  5. Unlocks mutex

lua_lock/unlock is not implemented, GC is stopped, when lua works with coroutine.

My question is, can I perform steps 2 and 3 without locking, if initialisation process does not requires any global Lua structs? Can i perform all this process without locking at all, if coroutine does not requires globals too?

In what case I generally can use Lua functions without locking?

Upvotes: 3

Views: 841

Answers (2)

mihacooper
mihacooper

Reputation: 21

Lua does not guarantee thread safety if you're trying to use single Lua state in separate OS threads without lua_lock/unlock. If you want to use multithreaded environment you need to use individual state for each OS thread.

Look at some multithreading solutions, e.g. https://github.com/effil/effil.

Upvotes: 2

Nicol Bolas
Nicol Bolas

Reputation: 473312

In what case I generally can use Lua functions without locking?

On the same Lua state (or threads derived from the same source Lua state)?

None.

Lua is thread-safe in the sense that separate Lua state instances can be executed in parallel. There are absolutely no thread safety guarantees when you call any Lua API function from two different threads on the same Lua state instance.

You cannot do any of the steps 2, 3, or 4 outside of some synchronization mechanism to prevent concurrent access to the same state. It doesn't matter if it's just creating a new thread (which allocates memory) or some "initialization process" (which will likely allocate memory). Even things that don't allocate memory are still not allowed.

Lua offers no guarantees about thread-safety within a Lua state.

Upvotes: 1

Related Questions