线程本地人在Lua [英] Thread locals in Lua

查看:113
本文介绍了线程本地人在Lua的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,Lua脚本可以订阅来自客户端的某些事件。也可以有一个脚本订阅多个客户端。目前,我每次设置全局客户端,我想调用脚本,以便脚本可以访问的客户端进行回调。我想要的是像C ++中的本地线程,以便我可以为每个客户端创建一个新的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:可能在Lua中有变量,只有在具体的Lua线程?

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

推荐答案

Lua没有内置的线程局部变量,但是你可以为每个Lua线程存储线程局部变量,并使用 coroutine.running (或C中的 lua_pushthread )确定哪个线程正在运行)。然后使它更方便metatables。例如:

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

这篇关于线程本地人在Lua的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆