emit 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: f7f3459190a3ae6b0f8d872f97e14cbe8524468e
4
+ data.tar.gz: 417ad5f6609d7ec63cabab3c0349e854842e2888
5
+ SHA512:
6
+ metadata.gz: 8755bc73dd138ba8ea36a02613e7a6c99ea4a9ad0d5e3f9542ad2a592a398b7e18bf6f9a027b536f692ebf147de2c4a248a7aeda4cfed0967777c4cadb2e0e40
7
+ data.tar.gz: ab3bce60704fe9de7b22af564721704ea9fcb6f088bce47373085f9decab9aaca23c60172e73636b448394567dc89b2f4831117ae3928a376a97189e1b0cbd08
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
@@ -0,0 +1,17 @@
1
+ sudo: false
2
+ language: ruby
3
+
4
+ os:
5
+ - osx
6
+ - linux
7
+
8
+ rvm:
9
+ - 2.4.2
10
+ - 2.5.0
11
+
12
+ before_install:
13
+ - gem install bundler -v 1.16.1
14
+ - bundle
15
+
16
+ script:
17
+ - bundle exec rspec
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at mads.ohm@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in emit.gemspec
6
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Mads Ohm Larsen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,35 @@
1
+ # Emit
2
+
3
+ [![Build Status](https://travis-ci.org/omegahm/emit.svg?branch=master)](https://travis-ci.org/omegahm/emit)
4
+
5
+ Emit is an implementation of Hoare's CSP in Ruby.
6
+
7
+ Emit supports channels and processes to communicate and be run in parallel utilizing Ruby fibers.
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'emit'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install emit
24
+
25
+ ## Contributing
26
+
27
+ Bug reports and pull requests are welcome on GitHub at https://github.com/omegahm/emit. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
28
+
29
+ ## License
30
+
31
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
32
+
33
+ ## Code of Conduct
34
+
35
+ Everyone interacting in the Emit project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/omegahm/emit/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["test/**/*_test.rb"]
8
+ end
9
+
10
+ task :default => :test
@@ -0,0 +1,66 @@
1
+ require "emit"
2
+
3
+ def prefix(cin, cout, item)
4
+ loop do
5
+ cout << item
6
+ item = cin.()
7
+ end
8
+ end
9
+
10
+ def delta2(cin, cout1, cout2)
11
+ loop do
12
+ t = cin.()
13
+ cout1 << t
14
+ cout2 << t
15
+ end
16
+ end
17
+
18
+ def successor(cin, cout)
19
+ loop do
20
+ cout << cin.() + 1
21
+ end
22
+ end
23
+
24
+ def consumer(cin, n)
25
+ cin.()
26
+
27
+ cin.()
28
+ t1 = Time.now
29
+ n.times { cin.() }
30
+ t2 = Time.now
31
+
32
+ dt = t2 - t1
33
+ tchan = dt.fdiv(4 * n)
34
+
35
+ puts "Total time elapsed = %.6fs" % dt
36
+ puts "Avg. time per communication = %.6fs = %.6fµs" % [tchan, tchan * 1_000_000]
37
+ puts
38
+
39
+ Emit.poison(cin)
40
+ end
41
+
42
+ n = 3
43
+ comms = 500
44
+ n.times do |i|
45
+ puts "Running with #{4*comms} communications"
46
+ puts
47
+
48
+ begin
49
+ puts "---------- run: #{i+1} / #{n} ----------"
50
+
51
+ a = Emit.channel
52
+ b = Emit.channel
53
+ c = Emit.channel
54
+ d = Emit.channel
55
+ puts "Running commstime"
56
+
57
+ Emit.parallel(
58
+ Emit.prefix(+c, -a, 0),
59
+ Emit.delta2(+a, -b, -d),
60
+ Emit.successor(+b, -c),
61
+ Emit.consumer(+d, comms)
62
+ )
63
+ rescue Emit::ChannelPoisonedException
64
+ Emit::Scheduler.reset!
65
+ end
66
+ end
@@ -0,0 +1,37 @@
1
+ require "emit"
2
+
3
+ def master(cout)
4
+ 100000.times do |i|
5
+ cout << i
6
+ end
7
+ Emit.poison(cout)
8
+ end
9
+
10
+ def worker(cin, cout)
11
+ loop do
12
+ cout << 2*cin.()
13
+ end
14
+ rescue Emit::ChannelPoisonedException
15
+ Emit.poison(cout)
16
+ end
17
+
18
+ def sink(cin)
19
+ loop do
20
+ cin.()
21
+ end
22
+ rescue Emit::ChannelPoisonedException
23
+ # no-op
24
+ end
25
+
26
+ ch1 = Emit.channel
27
+ ch2 = Emit.channel
28
+
29
+ t1 = Time.now
30
+ Emit.parallel(
31
+ Emit.master(-ch1),
32
+ 10 * Emit.worker(+ch1, -ch2),
33
+ Emit.sink(+ch2)
34
+ )
35
+ t2 = Time.now
36
+
37
+ puts "Total time elapsed = %.6fs" % (t2-t1)
@@ -0,0 +1,40 @@
1
+ require "emit"
2
+
3
+ def producer(job_out, bagsize, bags)
4
+ bags.times { job_out << bagsize }
5
+ Emit.retire(job_out)
6
+ end
7
+
8
+ def worker(job_in, result_out)
9
+ loop do
10
+ cnt = job_in.()
11
+ sum = cnt.times.count { (rand**2 + rand**2) < 1 }
12
+ result_out << (4.0 * sum) / cnt
13
+ end
14
+ rescue Emit::ChannelRetiredException
15
+ Emit.retire(result_out)
16
+ end
17
+
18
+ def consumer(result_in)
19
+ cnt = 0
20
+ sum = result_in.()
21
+ loop do
22
+ cnt += 1
23
+ sum = (sum * cnt + result_in.()) / (cnt+1)
24
+ end
25
+ rescue Emit::ChannelRetiredException
26
+ puts sum
27
+ end
28
+
29
+ jobs = Emit.channel
30
+ results = Emit.channel
31
+
32
+ t1 = Time.now
33
+ Emit.parallel(
34
+ Emit.producer(-jobs, 1000, 10000),
35
+ 10.times.map { Emit.worker(+jobs, -results) },
36
+ Emit.consumer(+results)
37
+ )
38
+ t2 = Time.now
39
+
40
+ puts "Total time elapsed = %.6fs" % (t2-t1)
@@ -0,0 +1,30 @@
1
+ require "emit"
2
+
3
+ @result = []
4
+ def action(message: nil)
5
+ @result << message
6
+ end
7
+
8
+ def p1(cout, n)
9
+ n.times { |i| cout << i }
10
+ end
11
+
12
+ def p2(cin1, cin2, n)
13
+ n.times do
14
+ Emit.select(
15
+ Emit::InputGuard.new(cin1, action: method(:action)),
16
+ Emit::InputGuard.new(cin2, action: method(:action))
17
+ )
18
+ end
19
+ end
20
+
21
+ ch1 = Emit.channel
22
+ ch2 = Emit.channel
23
+
24
+ Emit.parallel(
25
+ Emit.process(-ch1, 50, &method(:p1)),
26
+ Emit.process(-ch2, 50, &method(:p1)),
27
+ Emit.process(+ch1, +ch2, 100, &method(:p2))
28
+ )
29
+
30
+ puts @result.inspect
@@ -0,0 +1,22 @@
1
+ require "emit"
2
+
3
+ c = Emit.channel
4
+ d = Emit.channel
5
+
6
+ def p(cout, cin)
7
+ puts "START"
8
+ cout << 1
9
+ puts "WRITE"
10
+ cin.()
11
+ puts "DONE"
12
+ end
13
+
14
+ def q(cout, cin)
15
+ cout << 1
16
+ cin.()
17
+ end
18
+
19
+ Emit.parallel(
20
+ Emit.p(-c, +d),
21
+ Emit.q(-d, +c)
22
+ )
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "emit"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,26 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "emit/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "emit"
8
+ spec.version = Emit::VERSION
9
+ spec.authors = ["Mads Ohm Larsen"]
10
+ spec.email = ["mads.ohm@gmail.com"]
11
+
12
+ spec.summary = "CSP for Ruby"
13
+ spec.description = "Communicating Sequential Processes with Ruby fibers"
14
+ spec.homepage = "https://github.com/omegahm/emit"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_development_dependency "bundler", "~> 1.16"
24
+ spec.add_development_dependency "rake", "~> 10.0"
25
+ spec.add_development_dependency "rspec", "~> 3.7"
26
+ end
@@ -0,0 +1,76 @@
1
+ require "fiber"
2
+
3
+ require "emit/version"
4
+ require "emit/exceptions"
5
+
6
+ require "emit/scheduler"
7
+ require "emit/process"
8
+ require "emit/channel_request"
9
+ require "emit/channel"
10
+
11
+ require "emit/channel_end"
12
+ require "emit/channel_end_read"
13
+ require "emit/channel_end_write"
14
+
15
+ require "emit/input_guard"
16
+ require "emit/output_guard"
17
+
18
+ require "emit/alternation"
19
+ require "emit/choice"
20
+
21
+ module Emit
22
+ class << self
23
+ def parallel(*processes)
24
+ processes.flatten!
25
+
26
+ processes.each do |process|
27
+ process.start
28
+ Scheduler.enqueue(process)
29
+ end
30
+
31
+ Scheduler.join(processes)
32
+ processes.map(&:return_value)
33
+ end
34
+
35
+ def sequence(*processes)
36
+ processes.flatten.each(&:run)
37
+ end
38
+
39
+ def channel
40
+ Channel.new
41
+ end
42
+
43
+ def process(*args, **kwargs, &block)
44
+ Process.new(*args, **kwargs, &block)
45
+ end
46
+
47
+ def poison(*channel_ends)
48
+ channel_ends.each(&:poison)
49
+ end
50
+
51
+ def retire(*channel_ends)
52
+ channel_ends.each(&:retire)
53
+ end
54
+
55
+ def select(*guards)
56
+ Alternation.new(guards.map(&:guard_action)).execute
57
+ end
58
+
59
+ def method_missing(name, *args, **kwargs)
60
+ Emit.process(*args, **kwargs, &method(name.to_sym))
61
+ end
62
+ end
63
+
64
+ private_constant :ChannelEnd
65
+ private_constant :ChannelEndRead
66
+ private_constant :ChannelEndWrite
67
+ private_constant :ChannelRequest
68
+ end
69
+
70
+ class Integer
71
+ alias :old_mult :*
72
+ def *(other)
73
+ return other * self if Emit::Process === other
74
+ old_mult(other)
75
+ end
76
+ end
@@ -0,0 +1,106 @@
1
+ module Emit
2
+ class Alternation
3
+ def initialize(guards)
4
+ @guards = guards
5
+ end
6
+
7
+ def execute
8
+ idx, request, channel, operation = choose
9
+
10
+ if @guards[idx]
11
+ action = @guards[idx].last[:action]
12
+
13
+ case action
14
+ when Choice
15
+ case operation
16
+ when :write then action.invoke_on_output
17
+ when :read then action.invoke_on_input(request.message)
18
+ end
19
+ when Proc, Method
20
+ case operation
21
+ when :write then action.()
22
+ when :read then action.(message: request.message)
23
+ end
24
+ when nil
25
+ # no-op
26
+ else
27
+ fail "Failed executing action: #{action}."
28
+ end
29
+ end
30
+
31
+ [channel, request.message]
32
+ end
33
+
34
+ private
35
+
36
+ def choose
37
+ requests = {}
38
+ act = nil
39
+ poison = false
40
+ retire = false
41
+
42
+ Scheduler.current.state = :active
43
+
44
+ begin
45
+ idx = 0
46
+ @guards.each do |guard|
47
+ if guard.size == 3 # write
48
+ operation = :write
49
+ channel, message, action = guard
50
+ request = ChannelRequest.new(Scheduler.current, message)
51
+ channel.send(:post_write, request)
52
+ elsif guard.size == 2 # read
53
+ operation = :read
54
+ channel, action = guard
55
+ request = ChannelRequest.new(Scheduler.current)
56
+ channel.send(:post_read, request)
57
+ else
58
+ fail "Guard was neither write or read."
59
+ end
60
+
61
+ requests[request] = [idx, channel, operation]
62
+ idx += 1
63
+ end
64
+ rescue ChannelPoisonedException, ChannelRetiredException
65
+ act = result(requests).first
66
+ raise unless act
67
+ end
68
+
69
+ Scheduler.current.wait unless act
70
+
71
+ unless act
72
+ act, poisoned, retired = result(requests)
73
+ unless act
74
+ raise ChannelPoisonedException if poisoned
75
+ raise ChannelRetiredException if retired
76
+ abort "We should not get here in choice."
77
+ end
78
+ end
79
+
80
+ idx, channel, operation = requests[act]
81
+ [idx, act, channel, operation]
82
+ end
83
+
84
+ def result(requests)
85
+ act = nil
86
+ poisoned = false
87
+ retired = false
88
+
89
+ requests.each do |request, value|
90
+ _, channel, operation = value
91
+
92
+ if operation == :read
93
+ channel.send(:remove_read, request)
94
+ else
95
+ channel.send(:remove_write, request)
96
+ end
97
+
98
+ act = request if request.success?
99
+ poisoned ||= request.poisoned?
100
+ retired ||= request.retired?
101
+ end
102
+
103
+ [act, poisoned, retired]
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,167 @@
1
+ require "securerandom"
2
+
3
+ module Emit
4
+ class Channel
5
+ def initialize(name=nil)
6
+ @name = name || SecureRandom.uuid
7
+ @read_queue = []
8
+ @readers = 0
9
+ @write_queue = []
10
+ @writers = 0
11
+ @state = :alive
12
+ end
13
+
14
+ def read
15
+ check_termination!
16
+
17
+ process = Scheduler.current
18
+
19
+ fast_read(process).tap do |msg|
20
+ return msg unless msg.nil?
21
+ end
22
+
23
+ process.state = :active
24
+ request = ChannelRequest.new(process)
25
+ post_read(request)
26
+ request.process.wait
27
+ remove_read(request)
28
+
29
+ return request.message if request.success?
30
+
31
+ check_termination!
32
+ abort "Should not get here..."
33
+ end
34
+
35
+ def write(message)
36
+ check_termination!
37
+
38
+ process = Scheduler.current
39
+
40
+ fast_write(process, message).tap do |written|
41
+ return true unless written.nil?
42
+ end
43
+
44
+ process.state = :active
45
+ request = ChannelRequest.new(process, message)
46
+ post_write(request)
47
+ request.process.wait
48
+ remove_write(request)
49
+
50
+ return true if request.success?
51
+
52
+ check_termination!
53
+ abort "Should not get here..."
54
+ end
55
+
56
+ def poison
57
+ return if poisoned?
58
+ @state = :poisoned
59
+ @read_queue.each(&:poison)
60
+ @write_queue.each(&:poison)
61
+ end
62
+
63
+ def reader
64
+ @readers += 1
65
+ ChannelEndRead.new(self)
66
+ end
67
+ alias :+@ :reader
68
+
69
+ def writer
70
+ @writers += 1
71
+ ChannelEndWrite.new(self)
72
+ end
73
+ alias :-@ :writer
74
+
75
+ def poisoned?
76
+ @state == :poisoned
77
+ end
78
+
79
+ def retired?
80
+ @state == :retired
81
+ end
82
+
83
+ def leave_reader
84
+ return if retired?
85
+ @readers -= 1
86
+ if @readers.zero?
87
+ @state = :retired
88
+ @write_queue.each(&:retire)
89
+ end
90
+ end
91
+
92
+ def leave_writer
93
+ return if retired?
94
+ @writers -= 1
95
+ if @writers.zero?
96
+ @state = :retired
97
+ @read_queue.each(&:retire)
98
+ end
99
+ end
100
+
101
+ # private
102
+
103
+ def post_read(request)
104
+ check_termination!
105
+ @read_queue << request
106
+ match
107
+ end
108
+
109
+ def post_write(request)
110
+ check_termination!
111
+ @write_queue << request
112
+ match
113
+ end
114
+
115
+ def remove_read(request)
116
+ @read_queue.delete(request)
117
+ end
118
+
119
+ def remove_write(request)
120
+ @write_queue.delete(request)
121
+ end
122
+
123
+ private
124
+
125
+ def fast_read(process)
126
+ writer = @write_queue.shuffle.find(&:active?)
127
+ return nil if writer.nil?
128
+
129
+ writer.result = :success
130
+ writer.process.state = :done
131
+ Scheduler.activate(writer.process) unless process == writer.process
132
+
133
+ writer.message
134
+ end
135
+
136
+ def fast_write(process, message)
137
+ reader = @read_queue.shuffle.find(&:active?)
138
+ return nil if reader.nil?
139
+
140
+ reader.message = message
141
+ reader.result = :success
142
+ reader.process.state = :done
143
+ Scheduler.activate(reader.process) unless process == reader.process
144
+
145
+ true
146
+ end
147
+
148
+ def check_termination!
149
+ case @state
150
+ when :poisoned
151
+ raise ChannelPoisonedException
152
+ when :retired
153
+ raise ChannelRetiredException
154
+ end
155
+ end
156
+
157
+ def match
158
+ @write_queue.shuffle.each do |writer|
159
+ @read_queue.shuffle.each do |reader|
160
+ return true if writer.offer(reader)
161
+ end
162
+ end
163
+
164
+ false
165
+ end
166
+ end
167
+ end
@@ -0,0 +1,19 @@
1
+ module Emit
2
+ class ChannelEnd
3
+ extend Forwardable
4
+
5
+ def initialize(channel)
6
+ @channel = channel
7
+ @retired = false
8
+ end
9
+ def_delegators :@channel, :poison
10
+
11
+ def reader?
12
+ false
13
+ end
14
+
15
+ def writer?
16
+ false
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,25 @@
1
+ module Emit
2
+ class ChannelEndRead < ChannelEnd
3
+ def_delegators :@channel, :post_read
4
+ def_delegators :@channel, :remove_read
5
+
6
+ def call
7
+ @channel.read
8
+ end
9
+ alias :read :call
10
+
11
+ def retire
12
+ return if @retired
13
+
14
+ @retired = true
15
+ @channel.leave_reader
16
+ [:call, :read, :post_read].each do |sym|
17
+ define_singleton_method(sym) { raise ChannelRetiredException }
18
+ end
19
+ end
20
+
21
+ def reader?
22
+ true
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,25 @@
1
+ module Emit
2
+ class ChannelEndWrite < ChannelEnd
3
+ def_delegators :@channel, :post_write
4
+ def_delegators :@channel, :remove_write
5
+
6
+ def call(message)
7
+ @channel.write(message)
8
+ end
9
+ alias :<< :call
10
+
11
+ def retire
12
+ return if @retired
13
+
14
+ @retired = true
15
+ @channel.leave_writer
16
+ [:call, :<<, :post_write].each do |sym|
17
+ define_singleton_method(sym) { raise ChannelRetiredException }
18
+ end
19
+ end
20
+
21
+ def writer?
22
+ true
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,52 @@
1
+ module Emit
2
+ class ChannelRequest
3
+ attr_accessor :message, :result, :process
4
+
5
+ def initialize(process, message=nil)
6
+ @message = message
7
+ @process = process
8
+ @result = :fail
9
+ end
10
+
11
+ def poison
12
+ return if success?
13
+ @result = :poison
14
+ @process.notify(:poison)
15
+ end
16
+
17
+ def retire
18
+ return if success?
19
+ @result = :retire
20
+ @process.notify(:retire)
21
+ end
22
+
23
+ def offer(recipient)
24
+ return false unless @process.active? && recipient.process.active?
25
+ recipient.message = @message
26
+
27
+ @result = :success
28
+ recipient.result = :success
29
+
30
+ @process.notify(:done)
31
+ recipient.process.notify(:done)
32
+
33
+ true
34
+ end
35
+
36
+ def active?
37
+ @process.active?
38
+ end
39
+
40
+ def success?
41
+ @result == :success
42
+ end
43
+
44
+ def poisoned?
45
+ @result == :poison
46
+ end
47
+
48
+ def retired?
49
+ @result == :retired
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,18 @@
1
+ module Emit
2
+ class Choice
3
+ def initialize(*args, **kwargs, &block)
4
+ @block = block
5
+ @args = args
6
+ @kwargs = kwargs
7
+ end
8
+
9
+ def invoke_on_output
10
+ @block.call(*@args, **@kwargs)
11
+ end
12
+
13
+ def invoke_on_input(message)
14
+ @kwargs[:message] = message
15
+ @block.call(*@args, **@kwargs)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,5 @@
1
+ module Emit
2
+ class DeadlockException < StandardError; end
3
+ class ChannelRetiredException < StandardError; end
4
+ class ChannelPoisonedException < StandardError; end
5
+ end
@@ -0,0 +1,13 @@
1
+ module Emit
2
+ class InputGuard
3
+ attr_reader :guard_action
4
+
5
+ def initialize(channel_end, action=nil)
6
+ if ChannelEndRead === channel_end
7
+ @guard_action = [channel_end, action]
8
+ else
9
+ fail "InputGuard must have a reading channel end."
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,13 @@
1
+ module Emit
2
+ class GuardGuard
3
+ attr_reader :guard_action
4
+
5
+ def initialize(channel_end, message, action=nil)
6
+ if ChannelEndWrite === channel_end
7
+ @guard_action = [channel_end, message, action]
8
+ else
9
+ fail "OutputGuard must have a writing channel end."
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,86 @@
1
+ require "forwardable"
2
+
3
+ module Emit
4
+ class Process
5
+ attr_accessor :state
6
+ attr_reader :return_value, :fiber
7
+
8
+ def initialize(*args, **kwargs, &block)
9
+ fail ArgumentError.new("Must have a block as argument for Emit::Process.") unless block_given?
10
+ @block = block
11
+ @args = args
12
+ @kwargs = kwargs
13
+
14
+ @state = nil
15
+ @executed = false
16
+ @return_value = nil
17
+
18
+ @fiber = nil
19
+ end
20
+
21
+ def wait
22
+ Scheduler.get_next.transfer while active?
23
+ end
24
+
25
+ def notify(new_state)
26
+ @state = new_state
27
+ Scheduler.activate(self) unless Scheduler.current == self
28
+ end
29
+
30
+ def start
31
+ @fiber = Fiber.new { run }
32
+ end
33
+
34
+ def transfer
35
+ @fiber.transfer
36
+ end
37
+
38
+ def run
39
+ @executed = false
40
+
41
+ begin
42
+ if @block.arity.negative?
43
+ @return_value = @block.call(*@args, **@kwargs)
44
+ elsif @block.arity > 0
45
+ @return_value = @block.call(*@args)
46
+ else
47
+ @return_value = @block.call
48
+ end
49
+ rescue ::Emit::ChannelPoisonedException => e
50
+ propagate_poison
51
+ raise e
52
+ rescue ::Emit::ChannelRetiredException => e
53
+ propagate_retire
54
+ raise e
55
+ end
56
+
57
+ @executed = true
58
+ end
59
+
60
+ def active?
61
+ @state == :active
62
+ end
63
+
64
+ def executed?
65
+ @executed
66
+ end
67
+
68
+ def *(number)
69
+ [*number.times.map { self.dup }]
70
+ end
71
+
72
+ private
73
+
74
+ def propagate_poison
75
+ @args.each do |arg|
76
+ arg.poison if arg.methods.include?(:poison)
77
+ end
78
+ end
79
+
80
+ def propagate_retire
81
+ @args.each do |arg|
82
+ arg.retire if arg.methods.include?(:retire)
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,90 @@
1
+ require "singleton"
2
+ require_relative "process"
3
+
4
+ module Emit
5
+ class MainProcess < Process
6
+ include Singleton
7
+
8
+ def initialize
9
+ @fiber = Fiber.current
10
+ end
11
+ end
12
+
13
+ class Scheduler
14
+ include Singleton
15
+
16
+ attr_reader :current
17
+
18
+ def initialize
19
+ reset!
20
+ end
21
+
22
+ def reset!
23
+ @root = MainProcess.instance
24
+ @current = @root
25
+ @new_queue = []
26
+ @next_queue = []
27
+ @fiber = Fiber.new { start_mainloop }
28
+ @done = false
29
+ end
30
+
31
+ def enqueue(process)
32
+ @new_queue << process
33
+ end
34
+ alias :<< :enqueue
35
+
36
+ def join(processes)
37
+ tmp = @current
38
+ @done = false
39
+
40
+ processes.each do |process|
41
+ until process.executed?
42
+ raise DeadlockException if @done
43
+ get_next.transfer
44
+ end
45
+ end
46
+
47
+ @current = tmp
48
+ end
49
+
50
+ def activate(process)
51
+ @next_queue << process
52
+ end
53
+
54
+ def get_next
55
+ if !@new_queue.empty?
56
+ @fiber
57
+ elsif !@next_queue.empty?
58
+ @current = @next_queue.shift
59
+ @current
60
+ else
61
+ @fiber
62
+ end
63
+ end
64
+
65
+ private
66
+
67
+ def start_mainloop
68
+ loop do
69
+ if !@new_queue.empty?
70
+ @current = @new_queue.pop
71
+ @current.transfer
72
+ elsif !@next_queue.empty?
73
+ @current = @next_queue.pop
74
+ @current.transfer
75
+ end
76
+
77
+ if @new_queue.empty? && @next_queue.empty?
78
+ @done = true
79
+ @root.fiber.transfer
80
+ end
81
+ end
82
+ end
83
+ end
84
+
85
+ # Need to create the singleton instance in main fiber.
86
+ Scheduler = Scheduler.instance.tap do
87
+ # We remove the class and replace it with the instance.
88
+ remove_const("Scheduler")
89
+ end
90
+ end
@@ -0,0 +1,3 @@
1
+ module Emit
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,115 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: emit
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mads Ohm Larsen
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-05-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.7'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.7'
55
+ description: Communicating Sequential Processes with Ruby fibers
56
+ email:
57
+ - mads.ohm@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".travis.yml"
64
+ - CODE_OF_CONDUCT.md
65
+ - Gemfile
66
+ - LICENSE.txt
67
+ - README.md
68
+ - Rakefile
69
+ - benchmarks/commstime.rb
70
+ - benchmarks/many_processes.rb
71
+ - benchmarks/montecarlopi.rb
72
+ - benchmarks/select.rb
73
+ - benchmarks/starvation.rb
74
+ - bin/console
75
+ - bin/setup
76
+ - emit.gemspec
77
+ - lib/emit.rb
78
+ - lib/emit/alternation.rb
79
+ - lib/emit/channel.rb
80
+ - lib/emit/channel_end.rb
81
+ - lib/emit/channel_end_read.rb
82
+ - lib/emit/channel_end_write.rb
83
+ - lib/emit/channel_request.rb
84
+ - lib/emit/choice.rb
85
+ - lib/emit/exceptions.rb
86
+ - lib/emit/input_guard.rb
87
+ - lib/emit/output_guard.rb
88
+ - lib/emit/process.rb
89
+ - lib/emit/scheduler.rb
90
+ - lib/emit/version.rb
91
+ homepage: https://github.com/omegahm/emit
92
+ licenses:
93
+ - MIT
94
+ metadata: {}
95
+ post_install_message:
96
+ rdoc_options: []
97
+ require_paths:
98
+ - lib
99
+ required_ruby_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ required_rubygems_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ requirements: []
110
+ rubyforge_project:
111
+ rubygems_version: 2.6.13
112
+ signing_key:
113
+ specification_version: 4
114
+ summary: CSP for Ruby
115
+ test_files: []