in-parallel 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: d30dddb3a9591ec7118dbc42ca412a65e9ded1b4
4
+ data.tar.gz: be2ccd64a8b5f06620c17182ea136613505f2695
5
+ SHA512:
6
+ metadata.gz: c1f74ba5e5b9545b236f6b456472c7f56c0e44972392ab14b60ef7aa5ba188558fc2c2e57be96e828309db894f775c77ce59123071f0aa0c1d3541617f887201
7
+ data.tar.gz: 313546515a040e5636fccb15729b4e192f6f76fa078ceb4ac09de47784d28c1b610047764058bddcb5b2a391d019ee6557f6c53f98f21f7e084f1ff0b8692511
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in in_parallel.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,129 @@
1
+ # in-parallel
2
+ A lightweight Ruby library with very simple syntax, making use of process.fork for parallelization
3
+
4
+ I know there are other libraries that do parallelization, but I wanted something very simple to consume, and this was fun. I plan on using this within a test framework to enable parallel execution of some of the framework's tasks, and allow people within thier tests to execute code in parallel when wanted. This solution does not check to see how many processors you have, it just forks as many processes as you ask for. That means that it will handle a handful of parallel processes well, but could definitely overload your system with ruby processes if you try to spin up a LOT of processes. If you're looking for something simple and light-weight and on either linux or mac, then this solution could be what you want.
5
+
6
+ If you are looking for something a little more production ready, you should take a look at the [parallel](https://github.com/grosser/parallel) project.
7
+
8
+ ## Methods:
9
+
10
+ ### InParallel.run_in_parallel(&block)
11
+ 1. You can put whatever methods you want to execute in parallel into a block, and each method will be executed in parallel (unless the method is defined in kernel).
12
+ 1. Any methods further down the stack won't be affected, only the ones directly within the block.
13
+ 2. You can assign the results to instance variables and it just works, no dealing with an array or map of results.
14
+ 3. Log STDOUT and STDERR chunked per process to the console so that it is easy to see what happened in which process.
15
+
16
+ ```ruby
17
+ def method_with_param(name)
18
+ ret_val = "hello #{name} \n"
19
+ puts ret_val
20
+ ret_val
21
+ end
22
+
23
+ def method_without_param
24
+ # A result more complex than a string will be marshalled and unmarshalled and work
25
+ ret_val = {:foo => "bar"}
26
+ puts ret_val
27
+ return ret_val
28
+ end
29
+
30
+ # Example:
31
+ # will spawn 2 processes, (1 for each method) wait until they both complete,
32
+ # and log chunked STDOUT/STDERR for each process:
33
+ InParallel.run_in_parallel {
34
+ @result_1 = method_with_param('world')
35
+ @result_2 = method_without_param
36
+ }
37
+
38
+ puts "#{@result_1}, #{@result_2[:foo]}"
39
+ ```
40
+
41
+ STDOUT would be:
42
+ ```
43
+ Forked process for 'method_with_param' - PID = '49398'
44
+ Forked process for 'method_without_param' - PID = '49399'
45
+
46
+ ------ Begin output for method_with_param - 49398
47
+ hello world
48
+ ------ Completed output for method_with_param - 49398
49
+
50
+ ------ Begin output for method_without_param - 49399
51
+ {:foo=>"bar"}
52
+ ------ Completed output for method_without_param - 49399
53
+ hello world, bar
54
+ ```
55
+
56
+ ### InParallel.run_in_background(ignore_results = true, &block)
57
+ 1. This does basically the same thing as run_in_parallel, except it does not wait for execution of all processes to complete, it returns immediately.
58
+ 2. You can optionally ignore results completely (default) or delay evaluating the results until later
59
+ 3. You can run multiple blocks in the background and then at some later point evaluate all of the results
60
+
61
+ ```ruby
62
+ TMP_FILE = '/tmp/test_file.txt'
63
+
64
+ def create_file_with_delay(file_path)
65
+ sleep 2
66
+ File.open(file_path, 'w') { |f| f.write('contents')}
67
+ return true
68
+ end
69
+
70
+ # Example 1 - ignore results
71
+ InParallel.run_in_background{
72
+ create_file_with_delay(TMP_FILE)
73
+ }
74
+
75
+ # Should not exist immediately upon block completion
76
+ puts(File.exists?(TMP_FILE)) # false
77
+ sleep(3)
78
+ # Should exist once the delay from create_file_with_delay is done
79
+ puts(File.exists?(TMP_FILE)) # true
80
+
81
+ # Example 2 - delay results
82
+ InParallel.run_in_background(false){
83
+ @result = create_file_with_delay(TMP_FILE)
84
+ }
85
+
86
+ # Do something else
87
+
88
+ InParallel.run_in_background(false){
89
+ @result2 = create_file_with_delay('/tmp/someotherfile.txt')
90
+ }
91
+
92
+ # @result has not been assigned yet
93
+ puts @result >> "unresolved_parallel_result_0"
94
+
95
+ # This assigns all instance variables within the block and writes STDOUT and STDERR from the process to console.
96
+ InParallel.get_background_results
97
+ puts @result # true
98
+ puts @result2 # true
99
+
100
+ ```
101
+
102
+ ### Array.each_in_parallel(&block)
103
+ 1. This is very similar to other solutions, except that it directly extends the Array class with an each_in_parallel method, giving you the ability to pretty simply spawn a process for any item in an array.
104
+ 2. Identifies the block location (or caller location if the block does not have a source_location) in the console log to make it clear which block is being executed
105
+
106
+ ```ruby
107
+ ["foo", "bar", "baz"].each_in_parallel { |item|
108
+ puts |item|
109
+ }
110
+
111
+ ```
112
+ STDOUT:
113
+ ```
114
+ 'each_in_parallel' spawned process for '/Users/samwoods/parallel_test/test/paralell_spec.rb:77:in `block (2 levels) in <top (required)>'' - PID = '51600'
115
+ 'each_in_parallel' spawned process for '/Users/samwoods/parallel_test/test/paralell_spec.rb:77:in `block (2 levels) in <top (required)>'' - PID = '51601'
116
+ 'each_in_parallel' spawned process for '/Users/samwoods/parallel_test/test/paralell_spec.rb:77:in `block (2 levels) in <top (required)>'' - PID = '51602'
117
+
118
+ ------ Begin output for /Users/samwoods/parallel_test/test/paralell_spec.rb:77:in `block (2 levels) in <top (required)>' - 51600
119
+ foo
120
+ ------ Completed output for /Users/samwoods/parallel_test/test/paralell_spec.rb:77:in `block (2 levels) in <top (required)>' - 51600
121
+
122
+ ------ Begin output for /Users/samwoods/parallel_test/test/paralell_spec.rb:77:in `block (2 levels) in <top (required)>' - 51601
123
+ bar
124
+ ------ Completed output for /Users/samwoods/parallel_test/test/paralell_spec.rb:77:in `block (2 levels) in <top (required)>' - 51601
125
+
126
+ ------ Begin output for /Users/samwoods/parallel_test/test/paralell_spec.rb:77:in `block (2 levels) in <top (required)>' - 51602
127
+ baz
128
+ ------ Completed output for /Users/samwoods/parallel_test/test/paralell_spec.rb:77:in `block (2 levels) in <top (required)>' - 51602
129
+ ```
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
@@ -0,0 +1,32 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require_relative 'in_parallel/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "in-parallel"
8
+ spec.version = InParallel::VERSION
9
+ spec.authors = ["samwoods1"]
10
+ spec.email = ["sam.woods@puppetlabs.com"]
11
+
12
+ spec.summary = "A lightweight library to execute a handful of tasks in parallel with simple syntax"
13
+ spec.description = "I know there are other libraries that do parallelization, but I wanted something very " +
14
+ "simple to consume, and this was fun. I plan on using this within a test framework to enable parallel " +
15
+ "execution of some of the framework's tasks, and allow people within thier tests to execute code in " +
16
+ "parallel when wanted. This solution does not check to see how many processors you have, it just forks " +
17
+ "as many processes as you ask for. That means that it will handle a handful of parallel processes well, " +
18
+ "but could definitely overload your system with ruby processes if you try to spin up a LOT of processes. " +
19
+ "If you're looking for something simple and light-weight and on either linux or mac, then this solution " +
20
+ "could be what you want. If you are looking for something a little more production ready, you should take " +
21
+ "a look at the parallel project."
22
+ spec.homepage = "https://github.com/samwoods1/in-parallel"
23
+ spec.license = "MIT"
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_development_dependency "bundler", "~> 1.11"
31
+ spec.add_development_dependency "rake", "~> 10.0"
32
+ end
@@ -0,0 +1,3 @@
1
+ module InParallel
2
+ VERSION = Version = '0.1.0'
3
+ end
@@ -0,0 +1,21 @@
1
+ # Monkey patching Array to make it easy to do any .each in parallel
2
+ # Example - Will run puppet agent -t on each agent in parallel:
3
+ # agents.each_in_parallel { |agent|
4
+ # on agent, 'puppet agent -t'
5
+ # }
6
+ class Array
7
+ def each_in_parallel(&block)
8
+ if Process.respond_to?(:fork)
9
+ method_sym = "#{caller_locations[0]}"
10
+ each do |item|
11
+ out = InParallel._execute_in_parallel(method_sym) {block.call(item)}
12
+ puts "'each_in_parallel' forked process for '#{method_sym}' - PID = '#{out[:pid]}'\n"
13
+ end
14
+ # return the array of values, no need to look up from the map.
15
+ return InParallel.wait_for_processes.values
16
+ end
17
+ puts 'Warning: Fork is not supported on this OS, executing block normally'
18
+ block.call
19
+ each(&block)
20
+ end
21
+ end
@@ -0,0 +1,182 @@
1
+ require_relative 'array'
2
+
3
+ class InParallel
4
+ @@supported = Process.respond_to?(:fork)
5
+ @@outs = []
6
+ def self.outs
7
+ @@outs
8
+ end
9
+
10
+ @@background_objs = []
11
+ @@result_id = 0
12
+
13
+ # Example - will spawn 2 processes, (1 for each method) wait until they both complete, and log STDOUT:
14
+ # InParallel.run_in_parallel {
15
+ # @result_1 = on agents[0], 'puppet agent -t'
16
+ # @result_2 = on agents[1], 'puppet agent -t'
17
+ # }
18
+ # NOTE: Only supports assigning instance variables within the block, not local variables
19
+ def self.run_in_parallel(&block)
20
+ if @@supported
21
+ proxy = BlankBindingParallelProxy.new(self)
22
+ proxy.instance_eval(&block)
23
+ results_map = wait_for_processes
24
+ # pass in the 'self' from the block.binding which is the instance of the class
25
+ # that contains the initial binding call.
26
+ # This gives us access to the local and instance variables from that context.
27
+ return result_lookup(proxy, eval("self", block.binding), results_map)
28
+ end
29
+ puts 'Warning: Fork is not supported on this OS, executing block normally'
30
+ block.call
31
+ end
32
+
33
+ # Private method to lookup results from the results_map and replace the
34
+ # temp values with actual return values
35
+ def self.result_lookup(proxy_obj, target_obj, results_map)
36
+ vars = (proxy_obj.instance_variables)
37
+ results_map.keys.each { |tmp_result|
38
+ vars.each {|var|
39
+ if proxy_obj.instance_variable_get(var) == tmp_result
40
+ target_obj.instance_variable_set(var, results_map[tmp_result])
41
+ break
42
+ end
43
+ }
44
+ }
45
+
46
+ end
47
+ private_class_method :result_lookup
48
+
49
+ # Example - Will spawn a process in the background to run puppet agent on two agents and return immediately:
50
+ # Parallel.run_in_background {
51
+ # @result = on agents[0], 'puppet agent -t'
52
+ # @result_2 = on agents[1], 'puppet agent -t'
53
+ # }
54
+ # # Do something else here before waiting for the process to complete
55
+ #
56
+ # # Optionally wait for the processes to complete before continuing.
57
+ # # Otherwise use run_in_background(true) to clean up the process status and output immediately.
58
+ # Parrallel.get_background_results(self)
59
+ # NOTE: must call get_background_results to allow instance variables in calling object to be set,
60
+ # otherwise @result will evaluate to "unresolved_parallel_result_0"
61
+ def self.run_in_background(ignore_result = true, &block)
62
+ if @@supported
63
+ proxy = BlankBindingParallelProxy.new(self)
64
+ proxy.instance_eval(&block)
65
+
66
+ if ignore_result
67
+ Process.detach(@@outs.last[:pid])
68
+ @@outs.pop
69
+ else
70
+ @@background_objs << {:proxy => proxy, :target => eval("self", block.binding)}
71
+ return outs.last[:tmp_result]
72
+ end
73
+ return
74
+ end
75
+ puts 'Warning: Fork is not supported on this OS, executing block normally'
76
+ result = block.call
77
+ return nil if ignore_result
78
+ result
79
+ end
80
+
81
+ def self.get_background_results
82
+ results_map = wait_for_processes
83
+ # pass in the 'self' from the block.binding which is the instance of the class
84
+ # that contains the initial binding call.
85
+ # This gives us access to the local and instance variables from that context.
86
+ @@background_objs.each {|obj|
87
+ return result_lookup(obj[:proxy], obj[:target], results_map)
88
+ }
89
+ end
90
+
91
+ # Waits for all processes to complete and logs STDOUT and STDERR in chunks from any processes
92
+ # that were triggered from this Parallel class
93
+ def self.wait_for_processes
94
+ return unless @@supported
95
+ # Wait for all processes to complete
96
+ statuses = Process.waitall
97
+
98
+ results_map = {}
99
+ # Print the STDOUT and STDERR for each process with signals for start and end
100
+ while !@@outs.empty? do
101
+ out = @@outs.shift
102
+ begin
103
+ puts "\n------ Begin output for #{out[:method_sym]} - #{out[:pid]}\n"
104
+ puts out[:std_out].readlines
105
+ puts "------ Completed output for #{out[:method_sym]} - #{out[:pid]}\n"
106
+ results_map[out[:tmp_result]] = Marshal.load(out[:result].read)
107
+ ensure
108
+ # close the read end pipes
109
+ out[:std_out].close unless out[:std_out].closed?
110
+ out[:result].close unless out[:result].closed?
111
+ end
112
+ end
113
+
114
+ statuses.each { |status|
115
+ raise("Parallel process with PID '#{status[0]}' failed: #{status[1]}") unless status[1].success?
116
+ }
117
+
118
+ return results_map
119
+ end
120
+
121
+ # private method to execute some code in a separate process and store the STDOUT and STDERR for later retrieval
122
+ def self._execute_in_parallel(method_sym, obj = self, &block)
123
+ ret_val = nil
124
+ # Communicate the return value of the method or block
125
+ read_result, write_result = IO.pipe
126
+ # Store the STDOUT and STDERR of the method or block
127
+ read_io, write_io = IO.pipe
128
+ pid = fork do
129
+ STDOUT.reopen(write_io)
130
+ STDERR.reopen(write_io)
131
+ # Need to store this for the case of run_in_background in _execute
132
+ @@result_writer = write_result
133
+ begin
134
+ # close subprocess's copy of read_io since it only needs to write
135
+ read_io.close
136
+ read_result.close
137
+ ret_val = obj.instance_eval(&block)
138
+ # Write the result to the write_result IO stream.
139
+ # Have to serialize the value so it can be transmitted via IO
140
+ Marshal.dump(ret_val, write_result)
141
+ rescue SystemCallError => err
142
+ puts "error: #{err.message}"
143
+ write_io.write('.')
144
+ exit 1
145
+ ensure
146
+ write_io.close
147
+ write_result.close
148
+ end
149
+ end
150
+ write_io.close
151
+ write_result.close
152
+ # store the IO object with the STDOUT for each pid
153
+ out = { :pid => pid,
154
+ :method_sym => method_sym,
155
+ :std_out => read_io,
156
+ :result => read_result,
157
+ :tmp_result => "unresolved_parallel_result_#{@@result_id}" }
158
+ @@outs.push(out)
159
+ @@result_id += 1
160
+ out
161
+ end
162
+
163
+ # Proxy class used to wrap each method execution in a block and run it in parallel
164
+ # A block from Parallel.run_in_parallel is executed with a binding of an instance of this class
165
+ class BlankBindingParallelProxy < BasicObject
166
+ # Don't worry about running methods like puts or other basic stuff in parallel
167
+ include ::Kernel
168
+
169
+ def initialize(obj)
170
+ @object = obj
171
+ @result_id = 0
172
+ end
173
+
174
+ # All methods within the block should show up as missing (unless defined in :Kernel)
175
+ def method_missing(method_sym, *args, &block)
176
+ out = ::InParallel._execute_in_parallel(method_sym) {@object.send(method_sym, *args, &block)}
177
+ puts "Forked process for '#{method_sym}' - PID = '#{out[:pid]}'\n"
178
+ out[:tmp_result]
179
+ end
180
+
181
+ end
182
+ end
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: in-parallel
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - samwoods1
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-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.11'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: '1.11'
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
+ description: I know there are other libraries that do parallelization, but I wanted
42
+ something very simple to consume, and this was fun. I plan on using this within
43
+ a test framework to enable parallel execution of some of the framework's tasks,
44
+ and allow people within thier tests to execute code in parallel when wanted. This
45
+ solution does not check to see how many processors you have, it just forks as many
46
+ processes as you ask for. That means that it will handle a handful of parallel processes
47
+ well, but could definitely overload your system with ruby processes if you try to
48
+ spin up a LOT of processes. If you're looking for something simple and light-weight
49
+ and on either linux or mac, then this solution could be what you want. If you are
50
+ looking for something a little more production ready, you should take a look at
51
+ the parallel project.
52
+ email:
53
+ - sam.woods@puppetlabs.com
54
+ executables: []
55
+ extensions: []
56
+ extra_rdoc_files: []
57
+ files:
58
+ - Gemfile
59
+ - LICENSE
60
+ - README.md
61
+ - Rakefile
62
+ - in_parallel.gemspec
63
+ - in_parallel/version.rb
64
+ - lib/array.rb
65
+ - lib/in_parallel.rb
66
+ homepage: https://github.com/samwoods1/in-parallel
67
+ licenses:
68
+ - MIT
69
+ metadata: {}
70
+ post_install_message:
71
+ rdoc_options: []
72
+ require_paths:
73
+ - lib
74
+ required_ruby_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - '>='
77
+ - !ruby/object:Gem::Version
78
+ version: '0'
79
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - '>='
82
+ - !ruby/object:Gem::Version
83
+ version: '0'
84
+ requirements: []
85
+ rubyforge_project:
86
+ rubygems_version: 2.4.7
87
+ signing_key:
88
+ specification_version: 4
89
+ summary: A lightweight library to execute a handful of tasks in parallel with simple
90
+ syntax
91
+ test_files: []
92
+ has_rdoc: