Skip to content

Commit

Permalink
[lua] tz::lua::get_state() can now be called on any thread - the inte…
Browse files Browse the repository at this point in the history
…rnal lua states are unique to each thread. this means however that lua variables set on one thread will not exist on another - multithreaded lua code should thus be very carefully written
  • Loading branch information
harrand committed Aug 6, 2023
1 parent ebef8aa commit 61ba03d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/tz/lua/state.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <cstdint>
#include <map>
#include <filesystem>
#include <mutex>

extern "C"
{
Expand Down Expand Up @@ -240,20 +241,28 @@ namespace tz::lua
return this->last_error;
}

std::thread::id state::get_owner_thread_id() const
{
return this->owner;
}

bool state::impl_check_stack(std::size_t sz) const
{
auto* s = static_cast<lua_State*>(this->lstate);
return lua_checkstack(s, sz);
}

state defstate = {};

void tz_inject_state(state& s);

thread_local state defstate = {};
std::mutex state_creation_mtx;

state& get_state()
{
if(!defstate.valid())
{
// luaL_newstate needs external synchronisation. once it's done though every thread has its own lua state.
std::unique_lock<std::mutex>{state_creation_mtx};
lua_State* l = luaL_newstate();
luaL_openlibs(l);
defstate = state{static_cast<void*>(l)};
Expand Down
3 changes: 3 additions & 0 deletions src/tz/lua/state.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <type_traits>
#include <functional>
#include <optional>
#include <thread>

namespace tz::lua
{
Expand Down Expand Up @@ -64,10 +65,12 @@ namespace tz::lua
std::optional<std::uint64_t> get_uint(const char* varname) const;
std::string collect_stack() const;
const std::string& get_last_error() const;
std::thread::id get_owner_thread_id() const;
private:
bool impl_check_stack(std::size_t sz) const;
mutable std::string last_error = "";
void* lstate = nullptr;
std::thread::id owner = std::this_thread::get_id();
};

/**
Expand Down

0 comments on commit 61ba03d

Please sign in to comment.