Semaphore

Semaphore library - locking and synchronization mechanism for scripts #

Load the library:

require('sem')

Library functions #

sem.runlocked(name, timeout, callback, [param1, [param2, [...]]]) #

Runs callback function in locked mode, returning all callback results as is. First parameter passed to callback is lock status - true when lock was acquired, false when locking failed, nil when semaphore creation failed.

Parameters:

  • name - shared semaphore name
  • timeout - maximum time to wait in seconds for semaphore to become unlocked
  • callback - function to execute in locked mode
  • param1, param2, ... - optional additional parameters to pass to callback

Example (event script with locking):

require('sem')

-- wait for 5 seconds max before executing callback
res1, res2 = sem.runlocked('eventlock', 5, function(lockres)
  -- lock acquired
  if lockres then
    return true, 'lock ok'
  -- failed to acquire lock
  else
    return nil, 'lock failed'
  end
end)

log(res1, res2)

semaphore = sem.open(name, [value = 1]) #

Opens shared semaphore, returns semaphore handle or generates an error on failure.

Parameters:

  • name - shared semaphore name, required
  • value - initial value, optional, defaults to 1 (semaphore is unlocked)

semaphore:getvalue() #

Returns the current value of the semaphore or nil on error. Zero value means that the semaphore is locked.


semaphore:post() #

Increments (unlocks) the semaphore.


semaphore:trywait() #

Checks if the semaphore is locked, returns true and decrements the semaphore when the value is non-zero, false otherwise.


semaphore:wait([timeout]) #

Decrements the semaphore with optional timeout in seconds.

When no timeout is specified, this function will block until semaphore is incremented.

semaphore:close() #

Closes the semaphore. Not required, semaphore handles are closed automatically when script execution ends.