Skip to content

Instantly share code, notes, and snippets.

@asaaki
Created May 16, 2019 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asaaki/71b554ab037e487245a109c074a30f0f to your computer and use it in GitHub Desktop.
Save asaaki/71b554ab037e487245a109c074a30f0f to your computer and use it in GitHub Desktop.
Some Ruby stdlib experiments
### Experiments
# https://ruby-doc.org/core-2.5.0/SizedQueue.html
log = SizedQueue.new(100)
# https://ruby-doc.org/core-2.5.0/Queue.html
queue = Queue.new
# https://ruby-doc.org/core-2.5.0/ThreadGroup.html
group = ThreadGroup.new # pool
5.times do |i|
# https://ruby-doc.org/core-2.5.0/Thread.html
w = Thread.new("thread-#{i}") do |t|
m = log.pop
while m
# do the work
puts "T: #{t} | M: #{m}"
end
end
group.add(w)
end
group.enclose # no adding or removing of threads
group.list
log.num_waiting # how many threads are on this queue?
log.push('my item')
# simple unsized queue example
queue.push(1)
queue.pop
# queue.pop # would block thread!
queue.push(2)
queue.close
queue.pop
queue.pop # does not block / returns `nil`, since it's a closed queue
# https://ruby-doc.org/core-2.5.0/Fiber.html
_f = Fiber.new do
counter = 0
loop { counter += 1; Fiber.yield(counter) }
end
# https://ruby-doc.org/core-2.5.0/Mutex.html
m = Mutex.new
# https://ruby-doc.org/core-2.5.0/ConditionVariable.html
cv = ConditionVariable.new
t1 = Thread.new { m.synchronize { cv.wait(m); puts :t1_unlocked; cv.signal; puts :t1_end } }
t2 = Thread.new { m.synchronize { puts :t2_first; cv.signal; puts :t2_signalled; cv.wait(m); puts :t2_end } }
[t1, t2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment