Event script which cannot be executed in parallel, with timeout protection
Example: Event script which cannot be executed in parallel, with timeout protection
Task
How to make access protection to event-based script with semaphore?
Event based script
- require('sem')
-
- semaphore = sem.open('eventlock')
- timeout = 5 * 10
-
- -- wait for unlock or 5 second timeout
- while not semaphore:trywait() and timeout > 0 do
- sleep(0.1)
- timeout = timeout - 1
- end
-
- -- perform script actions
-
- -- unlock semaphore
- semaphore:post()
Semaphore documentation
Opens shared semaphore, returns semaphore handle or generates an error on failure:
- semaphore = sem.open(name, [value = 1])
Parameters:
- 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:
- semaphore:getvalue()
Increments (unlocks) the semaphore:
- semaphore:post()
Checks if the semaphore is locked, returns true and decrements the semaphore when the value is non-zero, false otherwise:
- semaphore:trywait()
Decrements the semaphore. Note! this function will block until semaphore is incremented. In most cases you should use trywait instead
- semaphore:wait()
Closes the semaphore. Not required, semaphore handles are closed automatically when script execution ends:
- semaphore:close())