Thread#raise
Thread#raiseã§ãä»»æã®ã¹ã¬ããã§å¼·å¶çã«ä¾å¤ãçºçããããã¨ãå¯è½ã§ãã
- ä¾å¤ãªã®ã§ãã¹ã¬ããå ã§ææ(catch)ãã¦å¦çãæ¯ãå¥ãããã¨ãã§ãã¾ãã
- ensureãããã¯ãã¡ããã¨å®è¡ããã¾ãã
t = Thread.fork { begin p "start" i = 0 while true p i+=1 sleep 0.2 end p "end" # ããã«ã¯æ¥ãªã ensure p "ensure" end } sleep 1 t.raise RuntimeError, "stop." t.value #ã¹ã¬ããå ã§çºçããä¾å¤ãã¹ãã¼ããã
å®è¡çµæã§ãã
"start" 1 2 3 4 5 "ensure" C:/xxx/thread_raise.rb:17: stop. (RuntimeError) from C:/xxx/thread_raise.rb:18:in `value' from C:/xxx/thread_raise.rb:18
ãªãã»ã©ãããã使ã£ã¦ã¹ã¬ããã®å®å ¨ãªåæ¢(ensureã§ã®å¾å§æ«ãä¿è¨¼ãããã¨ããæå³ã§)ãã§ããã®ãã¼ãã¨æã£ãã®ã ãã©ãThread#killãåãæåã«ãªã£ãã»ã»ã»ã
t = Thread.fork { begin p "start" i = 0 while true p i+=1 sleep 0.2 end p "end" # ããã«ã¯æ¥ãªã ensure p "ensure" end } sleep 1 #t.raise RuntimeError, "stop." t.kill t.value
å®è¡çµæã§ããensureãã¡ããã¨å®è¡ããã¦ãã¾ããã¡ãªã¿ã«ä¾å¤ã¯çºçãã¾ããã
"start" 1 2 3 4 5 "ensure"
killã¯å¼ã³åºãããæç¹ã§å¼·å¶çµäº(Javaã®System#exitã¿ãããªåä½ã«ãªãã¤ã¡ã¼ã¸)ã ã¨æã£ã¦ããã®ã ãã©ããããããã®ãªã®ã?