-
-
Save rightfold/a2003cf1414fdc533dd1 to your computer and use it in GitHub Desktop.
This file contains 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
std = std or {} | |
std.runtime = std.runtime or {} | |
std.runtime.queue = {} | |
function std.runtime.schedule(coro, value) | |
table.insert(std.runtime.queue, { coro = coro, value = value }) | |
end | |
local Channel = { } | |
function std.runtime.newChannel() | |
result = { | |
senders = {}, | |
receivers = {}, | |
} | |
setmetatable(result, { __index = Channel }) | |
return result | |
end | |
function Channel:send(value) | |
local coro = coroutine.running() | |
if #self.receivers > 0 then | |
local receiver = table.remove(self.receivers, 1) | |
receiver(value) | |
std.runtime.schedule(coro) | |
else | |
table.insert(self.senders, function() | |
std.runtime.schedule(coro) | |
return value | |
end) | |
end | |
coroutine.yield() | |
end | |
function Channel:receive(value) | |
local coro = coroutine.running() | |
if #self.senders > 0 then | |
local sender = table.remove(self.senders, 1) | |
local value = sender() | |
std.runtime.schedule(coro, value) | |
else | |
table.insert(self.receivers, function(x) | |
std.runtime.schedule(coro, x) | |
end) | |
end | |
return coroutine.yield() | |
end | |
function std.runtime.spawn(f) | |
local coro = coroutine.create(function() | |
return f() | |
end) | |
std.runtime.schedule(coro) | |
end | |
local c = std.runtime.newChannel() | |
std.runtime.spawn(function() | |
print('A: sending 42') | |
c:send(42) | |
print('A: sent 42') | |
end) | |
std.runtime.spawn(function() | |
print('B: receiving') | |
local value = c:receive() | |
print('B: received ' .. value) | |
end) | |
while #std.runtime.queue > 0 do | |
local entry = table.remove(std.runtime.queue, 1) | |
coroutine.resume(entry.coro, entry.value) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment