Skip to content

Commit

Permalink
feat(sync): add return value for cond:signal and cond:broadcast
Browse files Browse the repository at this point in the history
This is useful when user want to known whether any coroutines
have been awakened.

Signed-off-by: Jianhui Zhao <[email protected]>
  • Loading branch information
zhaojh329 committed Jun 3, 2024
1 parent 0ffa139 commit 2f46ead
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
7 changes: 5 additions & 2 deletions examples/sync_cond.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@ end

-- wakes one coroutine waiting on the cond
time.at(1, function()
cond:signal()
if cond:signal() then
print('waked one coroutine')
end
end)

-- wakes all coroutines waiting on the cond
time.at(3, function()
cond:broadcast()
local cnt = cond:broadcast()
print('waked', cnt, 'coroutines')
end)
9 changes: 9 additions & 0 deletions sync.lua
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,31 @@ function cond_methods:wait(timeout)
end

-- wakes one coroutine waiting on the cond, if there is any.
-- returns true if one coroutine was waked
function cond_methods:signal()
local watchers = self.watchers

if #watchers > 0 then
watchers[1]:send()
table.remove(watchers, 1)
return true
end

return false
end

-- wakes all coroutines waiting on the cond
-- returns the number of awakened coroutines
function cond_methods:broadcast()
local cnt = #self.watchers

for _, w in ipairs(self.watchers) do
w:send()
end

self.watchers = {}

return cnt
end

local cond_mt = { __index = cond_methods }
Expand Down

0 comments on commit 2f46ead

Please sign in to comment.