Thread locals in Lua

后端 未结 2 1367
夕颜
夕颜 2020-12-20 01:44

In my application a Lua script can subscribe to certain events from a Client. It is also possible to have one script subscribe to multiple Clients. Currently I am setting th

相关标签:
2条回答
  • 2020-12-20 02:29

    Lua doesn't have thread local variables built-in, but you could use a separate table for each Lua thread to store thread local variables, and figure out which thread is running using coroutine.running (or lua_pushthread in C). Then make it more convenient with metatables. Something like:

    local _G, coroutine = _G, coroutine
    local main_thread = coroutine.running() or {} -- returns nil in Lua 5.1
    local thread_locals = setmetatable( { [main_thread]=_G }, { __mode="k" } )
    local TL_meta = {}
    
    function TL_meta:__index( k )
      local th = coroutine.running() or main_thread
      local t = thread_locals[ th ]
      if t then
        return t[ k ]
      else
        return _G[ k ]
      end
    end
    
    function TL_meta:__newindex( k, v )
      local th = coroutine.running() or main_thread
      local t = thread_locals[ th ]
      if not t then
        t = setmetatable( { _G = _G }, { __index = _G } )
        thread_locals[ th ] = t
      end
      t[ k ] = v
    end
    
    -- convenient access to thread local variables via the `TL` table:
    TL = setmetatable( {}, TL_meta )
    -- or make `TL` the default for globals lookup ...
    if setfenv then
      setfenv( 1, TL ) -- Lua 5.1
    else
      _ENV = TL -- Lua 5.2+
    end
    
    0 讨论(0)
  • 2020-12-20 02:36

    Lua threads are child states from a single mother state. All global variables are shared by these Lua threads.

    Separate Lua states have separate globals.

    0 讨论(0)
提交回复
热议问题