2014-02-12 :-(
_ 午後
1300 デバッグしTARI
_ 買い物
iTunes Store
- 坂本真綾 Be mine! 「世界征服~謀略のズヴィズダー~」OP
- 悠木碧 ビジュメニア 世界征服~謀略のズヴィズダー~」ED
坂本真綾の曲を買うのは 10 年ぶりくらいか。
たぶんこの辺が最後。2003 年リリースだからほんとに 10 年だった。まあいろいろあった
B0035NO6LI
_ [Java][Ruby][マルチスレッド][デザインパターン]Java言語で学ぶデザインパターン入門マルチスレッド編 Single Threaded Execution - この橋を渡れるのは、たった一人
写経するために Ruby で書きなおしてみた。Java から Ruby へ
Ruby ぽく書ける箇所は多々あるんだろうけど愚直に 1 対 1 対応させる。
Java の Synchronize は Ruby には無いので Monitor を使う。
同時に 1 つのスレッドのみが処理を実行できる。クリティカルセクションとか呼ばれる
コード
# coding: utf-8 # # 『増補改訂版Java言語で学ぶデザインパターン入門マルチスレッド編』 http://www.hyuki.com/dp/dp2.html # # Single Threaded Execution - この橋を渡れるのは、たった一人 # require 'thread' require 'monitor' class Gate def initialize() @counter = 0 @name = "Nobody" @address = "Nowhere" @lock = Monitor.new end def pass(name, address) @lock.synchronize { @counter += 1 @name = name @address = address check() } end def to_s() @lock.synchronize { return "No. #{@counter}: #{@name} #{@address}" } end def check() puts to_s() if @name[0] != @address[0] puts "***** BROKEN ***** " + to_s() end end end class UserThread < Thread def initialize(gate, myname, myaddress) @gate = gate @myname = myname @myaddress = myaddress super() { puts @myname + " BEGIN" while true @gate.pass(@myname, @myaddress) sleep(1) end } end end def main(argv) gate = Gate.new threads ||= [] threads << UserThread.new(gate, "Alice", "Alaska") threads << UserThread.new(gate, "Bobby", "Brazil") threads << UserThread.new(gate, "Chris", "Canada") threads.each {|t| t.join() } end main(ARGV)
% ruby SingleThreadedExecution.rb Alice BEGIN No. 1: Alice Alaska Bobby BEGIN No. 2: Bobby Brazil Chris BEGIN No. 3: Chris Canada No. 4: Alice Alaska No. 5: Bobby Brazil No. 6: Chris Canada No. 7: Chris Canada No. 8: Bobby Brazil No. 9: Alice Alaska No. 10: Chris Canada No. 11: Alice Alaska No. 12: Bobby Brazil No. 13: Alice Alaska No. 14: Bobby Brazil No. 15: Chris Canada No. 16: Chris Canada No. 17: Alice Alaska No. 18: Bobby Brazil 以下略
著作権
Copyright (C) 2002,2006 Hiroshi Yuki. http://www.hyuki.com/dp/dp2.html hyuki@hyuki.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution.
参考
『増補改訂版Java言語で学ぶデザインパターン入門マルチスレッド編』
4797331623
[ツッコミを入れる]