30.04.2020, 04:38
Do not use sleep function from the example above. This function consumes all CPU resources but will not block anything. For normal delays use built-in sleep function.
If you need to prevent scripts from running the same code simultaneously then use semaphores.
This example will wait for up to 5 seconds for semaphore named eventlock to be become unlocked. If semaphore is unlocked then dosomething is executed. pcall is needed to catch any execution errors. Otherwise semaphore might remain locked if dosomething fails with an error.
If semaphore is still locked after 5 seconds then no function is executed.
This depends on what kind of locking you need. If you just need to some tasks in sequence (queue) then a resident script might be a better solution.
If you need to prevent scripts from running the same code simultaneously then use semaphores.
This example will wait for up to 5 seconds for semaphore named eventlock to be become unlocked. If semaphore is unlocked then dosomething is executed. pcall is needed to catch any execution errors. Otherwise semaphore might remain locked if dosomething fails with an error.
If semaphore is still locked after 5 seconds then no function is executed.
Code:
require('sem')
function dosomething()
-- do something here
end
stat, err = sem.runlocked('eventlock', 5, function(lockres)
if lockres then
return pcall(dosomething)
else
return nil, 'lock failed'
end
end)
if stat then
log('ok')
else
log('error', err)
end
This depends on what kind of locking you need. If you just need to some tasks in sequence (queue) then a resident script might be a better solution.