Skip to content

Curious : Thread safety? #378

Description

@shohnwal

I'm working with the Unreal 4 engine, which uses seperate threads in C++ for gameplay tasks and AI-stuff. My sol2-lua state is in the gameplay-thread.

I read on stackoverlow that normally accessing the lua state is not thread safe and can even mess up the lua stack.

I'm wondering : Is sol2s implementation of sol::thread and sol::coroutine providing thread-safety the the lua state?
If not, could you provide any advice how accessing a sol2 lua state from several threads could be done (mutexes in c++?)?

Right now i'm calling the lua state from the ai thread via

sol::thread thread = sol::thread::create(*this->GameModeLua);
sol::state_view view = thread.state();
sol::coroutine function = view["decide_command"];
sol::protected_function_result r = function(uniqueID, characterID, sol::as_table(this->combatevents));

but i'm unsure whether this actually provides any thread-safety.
The documentation about coroutines and threads
http://sol2.readthedocs.io/en/latest/api/thread.html
http://sol2.readthedocs.io/en/latest/api/coroutine.html
have sentences like "see thread for an example on how to get a coroutine that runs on a thread separate from your usual “main” lua_State." and "sol::thread is a separate runnable part of the Lua VM that can be used to execute work separately from the main thread," but it's not very clear if that means that these are c++ thread-safe.

Or should i use sol::main_thread( ... ) for a multithreaded c++ program?
If so, could you give an example how to use it? The documentation doesn't have any examples for this one.

If it's important, i'm using LuaJit.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions