lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 16 Oct 2006, at 14:19, Roberto Ierusalimschy wrote:

lua_sethook() is advertised as being signal-safe. I'm prepared to trust
Roberto's judgement that it is, although it seems to me that Posix
would prefer that some of those fields be declared as volatile
sig_atomic_t. However, I'm sure that Roberto has thought this through,
and certainly I haven't noticed any problems with it.

Thanks for the compliment. However, as I said before, it is mostly
impossible to really "think through" a piece of multithreading code.

Rethinking about the subject, I am afraid lua_sethook is not
"theoretically" safe even for signals (as it should be).

The problem is the non-atomicity of pointer accesses. There is a small
risk that, while luaD_callhook is reading L->hook, lua_sethook changes
it, so that luaD_callhook reads an invalid pointer.

I cannot see any simple way to correct this, without imposing some
restrictions on lua_sethook.

Let A and B be two sig_atomic_t values, each initialised to 0.

The reader of hook:
  repeat {
    read A
    read hook
    read B
  } until (A == B);

The writer of hook:
  let C = B + 1
  B = C
  write hook
  A = C

This works as long as the writer is called no more than 2^16 times between any read A and read B of a reader and as long as memory is ordered (which it is for all uniprocessor systems). So in particular if sethook is not used very much, then it'll work except on multithreaded multiprocessor systems with out-of-order memory. Maybe.

drj