Last active
May 18, 2025 21:36
-
-
Save truemedian/d260d028506400ebbefb9a6b95609d08 to your computer and use it in GitHub Desktop.
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 sem_t = {} | |
| sem_t.__index = sem_t | |
| function sem_t:wait() | |
| if self.value == 0 then -- cannot decrement, wait for increment | |
| local thread = coroutine.running() | |
| table.insert(self.threads, thread) | |
| coroutine.yield() | |
| end | |
| self.value = self.value - 1 | |
| end | |
| function sem_t:trywait() | |
| if self.value == 0 then | |
| return false | |
| end | |
| self.value = self.value - 1 | |
| return true | |
| end | |
| function sem_t:post() | |
| self.value = self.value + 1 | |
| if self.threads[1] then -- wake a thread if any are waiting | |
| local thread = table.remove(self.threads) | |
| local success, err = coroutine.resume(thread) | |
| if not success then | |
| error(debug.traceback(thread, err), 0) | |
| end | |
| end | |
| end | |
| local function sem_t.new(value) | |
| return setmetatable({ value = value or 0, threads = {} }, sem_t) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment