Last active
October 28, 2022 07:00
-
-
Save Fraktality/3f7659ab67b9d8fa1831c4182af6a5de to your computer and use it in GitHub Desktop.
Easy task lock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ | |
local fooInterlock = Interlock.new() | |
function foo() | |
local lock = fooInterlock:takeLock() | |
coroutine.yield() | |
if not lock:hasLock() then | |
return | |
end | |
bar() | |
end | |
--]] | |
local LocalLock = {} do | |
LocalLock.__index = LocalLock | |
function LocalLock.new(lock) | |
return setmetatable({ | |
_parent = lock, | |
_localState = lock._state, | |
}, LocalLock) | |
end | |
function LocalLock:hasLock() | |
return self._localState == self._parent._state | |
end | |
end | |
local Interlock = {} do | |
Interlock.__index = Interlock | |
function Interlock.new() | |
return setmetatable({ | |
_state = 0, | |
}, Interlock) | |
end | |
function Interlock:takeLock() | |
self._state = (self._state + 1)%2^53 | |
return LocalLock.new(self) | |
end | |
end | |
return Interlock |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment