代码之家  ›  专栏  ›  技术社区  ›  Peter

Ruby多线程:使一个线程等待另一个线程的信号

  •  2
  • Peter  · 技术社区  · 14 年前

    在Ruby中,我希望两个线程同时运行,并且希望后台线程定期向前台线程发送信号。如何让前台线程阻塞,直到后台线程显示“go”?我可以想出一些方法来做它,但我是在最合适的,惯用的Ruby方法之后。

    在代码中:

    loop do  # background, thread 1
      sleep 3
      receive_input
      tell_foreground_input_is_ready # <-- how do I do this?
    end
    

    loop do  # foreground, thread 2
      wait_for_signal_from_background  # <-- how do I do this?
      do_something
    end
    

    (注:背景可能会多次向前景发出信号。每次前台完成等待时,它都会重置backlog。)

    3 回复  |  直到 10 年前
        1
  •  1
  •   Mark Wilkins    14 年前

    您需要使用条件变量和互斥体,根据 this page

        2
  •  1
  •   Peter    14 年前

    结果证明这非常有效:

    require 'thread'
    queue = Queue.new
    Thread.new do
      100.times do |i|
        sleep 1
        queue.enq i
      end
    end
    
    loop do
      print "waiting... "
      puts queue.deq      # this function blocks.
    end
    
        3
  •  0
  •   fred271828    10 年前