From 2f46ead3ad45a4475988c6a45332949edc365ce4 Mon Sep 17 00:00:00 2001 From: Jianhui Zhao Date: Mon, 3 Jun 2024 14:36:27 +0800 Subject: [PATCH] feat(sync): add return value for cond:signal and cond:broadcast This is useful when user want to known whether any coroutines have been awakened. Signed-off-by: Jianhui Zhao --- examples/sync_cond.lua | 7 +++++-- sync.lua | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/examples/sync_cond.lua b/examples/sync_cond.lua index 1b89735..886869b 100755 --- a/examples/sync_cond.lua +++ b/examples/sync_cond.lua @@ -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) diff --git a/sync.lua b/sync.lua index 5ff6aa2..3fa8505 100644 --- a/sync.lua +++ b/sync.lua @@ -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 }