File: async_watcher.rb

package info (click to toggle)
ruby-cool.io 1.9.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 716 kB
  • sloc: ansic: 6,851; ruby: 1,730; makefile: 6
file content (43 lines) | stat: -rw-r--r-- 1,098 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#--
# Copyright (C)2007-10 Tony Arcieri
# You can redistribute this under the terms of the Ruby license
# See file LICENSE for details
#++

module Coolio
  # The AsyncWatcher lets you signal another thread to wake up.  Its
  # intended use is notifying another thread of events.
  class AsyncWatcher < IOWatcher
    def initialize
      @reader, @writer = ::IO.pipe
      super(@reader)
    end

    # Signal the async watcher.  This call is thread safe.
    def signal
      # Write a byte to the pipe.  What we write is meaningless, it
      # merely signals an event has occurred for each byte written.
      @writer.write "\0"
    end

    # Called whenever a signal is received
    def on_signal; end
    event_callback :on_signal

    #########
    protected
    #########

    def on_readable
      # Read a byte from the pipe.  This clears readability, unless
      # another signal is pending
      begin
        @reader.read_nonblock 1
      rescue Errno::EAGAIN
        # in case there are spurious wakeups from forked processs
        return
      end
      on_signal
    end
  end
end