Class: CSP::Channel

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/csp/channel.rb

Instance Method Summary collapse

Constructor Details

#initializeChannel

Returns a new instance of Channel.



8
9
10
11
# File 'lib/csp/channel.rb', line 8

def initialize
  @readers = []
  @writers = []
end

Instance Method Details

#<<(message) ⇒ Object



49
50
51
52
# File 'lib/csp/channel.rb', line 49

def << message
  write(message)
  return self
end

#eachObject



54
55
56
# File 'lib/csp/channel.rb', line 54

def each
  yield read while true
end

#read(options = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/csp/channel.rb', line 13

def read(options = {})
  message = callcc do |cont|
    @readers << cont

    if @writers.empty?
      if options[:callback]
        return
      else
        CSP.run
      end
    else
      @writers.shift.call
    end
  end

  if options[:callback]
    options[:callback].call(message)
  else
    return message
  end
end

#write(message) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/csp/channel.rb', line 35

def write(message)
  if @readers.empty?
    callcc do |cont|
      @writers << cont
      CSP.run
    end
  end

  callcc do |cont|
    CSP.enqueue(cont)
    @readers.shift.call(message)
  end
end