[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: lua_sethook() thread safety
- From: Roberto Ierusalimschy <roberto@...>
- Date: Wed, 9 Dec 2015 11:08:37 -0200
> I have a need to abort Lua states that are stuck in a compute-bound loop (e.g. "while true do end"). (And yes, “don’t do that” is a good answer, but I don’t have control of the entire corpus of Lua code running in the state).
>
> The best answer appears to be to adopt what lua.c does for handling signals: Do a lua_sethook() with a low instruction count and in the hook throw an exception with luaL_error(), [1]. In my case, this code would be called by a distinct OS thread (not a signal handler), so I’m looking carefully at the thread-safety of lua_sethook().
>
> The Lua source says that lua_sethook() can be called asynchronously, and I’ve spent some time reading lua-a archives (e.g. [2]) and studying the code. My reading of the source is that lua_sethook() *is* safe to call from a distinct OS thread (with some caveats), except i’m not clear about the code that manipulates L->oldpc in lua_sethook()? I’m not sufficiently familiar with the internals of the Lua VM to understand what it’s doing, and if it should be a concern or not?
'oldpc' is used only to avoid generating several line hooks for the same
line. If it contains garbage, the worst that can happen is that you get
an extra line hook once. 'basehookcount' and 'hookcount' follow a similar
logic for count hooks.
A more problematic point is 'hook', which is a pointer type.
According to the letter of ISO C, this assignment is not safe in a
signal handler, but we pretend it is. We also assign to 'hookmask',
so it probably should have type 'sig_atomic_t'. (Nevertheless, these
assignments do not seem to cause problems.)
-- Roberto