Example: Event script which cannot be executed in parallel, with timeout protection


How to make access protection to event-based script with semaphore?

Event based script

Source code    
  1. require('sem')
  3. semaphore = sem.open('eventlock')
  4. timeout = 5 * 10
  6. -- wait for unlock or 5 second timeout
  7. while not semaphore:trywait() and timeout > 0 do
  8. sleep(0.1)
  9. timeout = timeout - 1
  10. end
  12. -- perform script actions
  14. -- unlock semaphore
  15. semaphore:post()

Semaphore documentation

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

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


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


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

Source code    
  1. semaphore:getvalue()


Increments (unlocks) the semaphore:

Source code    
  1. semaphore:post()


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

Source code    
  1. semaphore:trywait()


Decrements the semaphore. Note! this function will block until semaphore is incremented. In most cases you should use trywait instead

Source code    
  1. semaphore:wait()


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

Source code    
  1. semaphore:close())