-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallelism_ruby.rb
74 lines (53 loc) · 1.35 KB
/
parallelism_ruby.rb
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
require 'time'
def long_duration(id)
puts "Starting id #{id} with pid #{$$}"
sleep 4
puts "Finished id #{id} with pid #{$$}"
end
def synchronous
start = Time.now
puts "Starting iterative solution"
(0..10).each do |num|
long_duration(num)
end
stop = Time.now
puts "Finishing iterative solution.\nRuntime #{stop - start}"
end
def threaded
start = Time.now
puts "Starting threaded solution"
threads = []
(0..10).each do |num|
threads << Thread.new { long_duration(num) }
end
threads.map(&:join)
stop = Time.now
puts "Finishing threaded solution.\nRuntime #{stop - start}"
end
def processes
start = Time.now
puts "Starting multiprocess solution"
processes = []
(0..10).each do |num|
processes << fork { long_duration(num) }
end
while true
process_runing = false
processes.each do |process_num|
begin
Process.getpgid(process_num) # Throws exception unless process is still active
process_running = true
rescue Errno::ESRCH
end
end
break unless process_running
end
stop = Time.now
puts "Finishing process solution.\nRuntime #{stop - start}"
end
puts "Iterative Solution launched from process id #{$$}"
synchronous()
puts "Threaded Solution launched from process id #{$$}"
threaded()
puts "Multi-Process Solution lauched from process id #{$$}"
processes()