This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm that you accept these cookies being set.

Blocking delay
#5
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.

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.
Reply


Messages In This Thread
Blocking delay - by benanderson_475 - 24.04.2020, 22:09
RE: Blocking delay - by AlexLV - 25.04.2020, 04:39
RE: Blocking delay - by benanderson_475 - 29.04.2020, 21:35
RE: Blocking delay - by admin - 25.04.2020, 07:38
RE: Blocking delay - by admin - 30.04.2020, 04:38
RE: Blocking delay - by AlexLV - 30.04.2020, 16:00

Forum Jump: