-
-
Save dminuoso/066090b0da2432bd26ded03cfb0cea22 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
queue = TBQueue.new 5 | |
a = Thread.new do | |
loop do | |
puts "producing" | |
Concurrent.atomically do | |
queue.write "hiya" | |
end | |
end | |
end | |
b = Thread.new do | |
loop do | |
sleep 1 | |
puts "consuming" | |
Concurrent.atomically do | |
a = queue.read | |
end | |
end | |
end |
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
class TBQueue | |
def initialize size | |
tvar = Concurrent::TVar | |
@r = tvar.new [] | |
@w = tvar.new [] | |
@rs = tvar.new 0 | |
@ws = tvar.new size | |
end | |
def write(a) | |
t = Concurrent::Transaction.current | |
w = t.read(@ws) | |
if w != 0 | |
t.write(@ws, w - 1) | |
else | |
r = t.read(@rs) | |
if r != 0 | |
t.write(@rs, 0) | |
t.write(@ws, r - 1) | |
else | |
Concurrent.abort_transaction | |
end | |
end | |
as = t.read(@w) | |
as.push(a) | |
t.write(@w, as) | |
end | |
def read | |
t = Concurrent::Transaction.current | |
xss = t.read(@r) | |
r = t.read(@rs) | |
t.write(@rs, r + 1) | |
if !xss.empty? | |
x, *xs = xss | |
t.write(@r, xs) | |
return x | |
else | |
ys = t.read(@w) | |
if ys.empty? | |
Concurrent.abort_transaction | |
else | |
z, *zs = ys | |
t.write(@w, []) | |
t.write(@r, zs) | |
return z | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment