Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

c++ - Thread locals in Lua

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 the global "Client" every time I want to call the script so that the script can access the Client that made the callback. What I would want is something like a thread local in C++ so that I could create a new Lua thread for every client and just set the "Client" variable for that thread once. If the client then fires the event it would just use the thread that it is associated with.

TLDR: Is it possible to have variables in Lua that are only valid within a specific Lua thread?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...