queue = Queue.new N = 10 sender = Thread.start do Thread.current[:data] = [] N.times do |i| sleep(rand(0..0.01)) queue << i Thread.current[:data] << i end end receiver = Thread.start do Thread.current[:data] = [] N.times do sleep(rand(0..0.001)) # shift出来ないとスレッドが自動停止してくれる Thread.current[:data] << queue.shift end end sender.join receiver.join # 正常にデータが受け取れている sender[:data] # => [0, 1, 2, 3, 4, 5, 6
![Rubyで書くスレッドのデザインパターン](https://cdn-ak-scissors.b.st-hatena.com/image/square/124612f5761e8da09a80ac8ce6e7fe0c1b5b1f72/height=288;version=1;width=512/https%3A%2F%2Fres.cloudinary.com%2Fzenn%2Fimage%2Fupload%2Fs--VC0vYk77--%2Fc_fit%252Cg_north_west%252Cl_text%3Anotosansjp-medium.otf_55%3ARuby%2525E3%252581%2525A7%2525E6%25259B%2525B8%2525E3%252581%25258F%2525E3%252582%2525B9%2525E3%252583%2525AC%2525E3%252583%252583%2525E3%252583%252589%2525E3%252581%2525AE%2525E3%252583%252587%2525E3%252582%2525B6%2525E3%252582%2525A4%2525E3%252583%2525B3%2525E3%252583%252591%2525E3%252582%2525BF%2525E3%252583%2525BC%2525E3%252583%2525B3%252Cw_1010%252Cx_90%252Cy_100%2Fg_south_west%252Cl_text%3Anotosansjp-medium.otf_37%3Amegeton%252Cx_203%252Cy_121%2Fg_south_west%252Ch_90%252Cl_fetch%3AaHR0cHM6Ly9zdG9yYWdlLmdvb2dsZWFwaXMuY29tL3plbm4tdXNlci11cGxvYWQvYXZhdGFyL2IyMGRmNGE4NjAuanBlZw%3D%3D%252Cr_max%252Cw_90%252Cx_87%252Cy_95%2Fv1627283836%2Fdefault%2Fog-base-w1200-v2.png)