[ruby-list:50590] [質問]thread内sleepコール 他threadよりsleep状態からrun状態にされた際、指定時間sleepさせるには?

From: <yamataka@...08.itscom.net>
Date: 2017-09-27 02:37:04 UTC
List: ruby-list #50590
山口と申します。

yama@roswell:~$ uname -a
CYGWIN_NT-6.3 JPC20165182 2.6.0(0.304/5/3) 2016-08-31 14:32 x86_64 
Cygwin
yama@roswell:~$ ruby --version
ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-cygwin]

の環境です。

2つのthread
input_thread,exec_thread
を用いて、

input_threadより、標準入力より p がタイプされると、
exec_thread を run状態からsleep状態
その状態から、p が入力されると、
exec_thread を sleep状態から run 状態にする (*)

という処理をしたく、サンプルコードを書いているのですが、

(*) の際、exec_thread内のsleep callで指定した時間 sleepせず、
すぐに sleep call処理が終わってしまいます。
指定した時間 sleep実行されるには、どのように記載すればよいか、ご教示いた
だけないでしょうか?

下記が、サンプルプログラムです。

exec_thread = Thread.new do
  loop do
    puts "in exec_thread"

    n = 100 # sleep 100s
    puts "in exec_thread sleep start #{n}s"
    sleep(n)

    puts "in exec_thread sleep end"
  end
end

input_thread = Thread.new do
  loop do
    ret = STDIN.gets
    case ret
    when /^ *p *$/ then # p: pause
      status = exec_thread.status
      case status
      when "run"
        puts "now: exec_thread.status: #{status}"
        puts "to : exec_thread.status: sleep"
        exec_thread.stop
      when "sleep"
        puts "now: exec_thread.status: #{status}"
        puts "to : exec_thread.status: run"
        exec_thread.run
      else # do nothing
      end
    when /^ *q *$/ then # quit
      exec_thread.kill
      break
    else
      # do nothing
    end
  end
end

exec_thread.join
input_thread.join



In This Thread

Prev Next