wahern / cqueues

Continuation Queues: Embeddable asynchronous networking, threading, and notification framework for Lua on Unix.
http://25thandclement.com/~william/projects/cqueues.html
MIT License
244 stars 37 forks source link

feature request: support for simple semaphore #214

Open ncopa opened 5 years ago

ncopa commented 5 years ago

It would be handy with a simple semaphore module so it is easy to limit number of concurrent running threads, without needing to reimplement it every time.

local condition = require"cqueues.condition"

local semaphore = {}
function semaphore.new(n)
        local self = { cond = condition.new(), count = n or 1 }
        return setmetatable(self, {__index = semaphore})
end

function semaphore.aquire(self)
        while self.count == 0 do
                self.cond:wait()
        end
        self.count = self.count - 1
end

function semaphore.release(self)
        self.count = self.count + 1
        self.cond:signal()
end
daurnimator commented 5 years ago

I feel like this would be a good sort of thing to distribute as a separate module. There was talk about moving some of the cqueues submodules out to separate rocks.