Skip to content

Commit

Permalink
readme: keep correct order in p_map example
Browse files Browse the repository at this point in the history
  • Loading branch information
0x1eef committed Jun 24, 2022
1 parent cf43614 commit 9d5101c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,21 @@ require "xchan"

def p_map(enum)
ch = xchan
enum.map { |e| Process.fork { ch.send yield(e) } }
enum.map
.with_index { |e, i| fork { sleep(e); ch.send yield([e * 2, i]) } }
.each { Process.wait(_1) }
enum.map { ch.recv }
.sort { _1.pop }
.map { _1[0] }
end

Kernel.p p_map([1,2,3]) { _1 * 2 }
t = Time.now
print p_map([3, 2, 1]) { _1 * 2 }, "\n"
print "Duration: #{Time.now - t}", "\n"

##
# == Output
# [2, 4, 6]
# [6, 4, 2]
# Duration: 3.00XXX
```

**Send a Ruby object to a child process**
Expand Down
13 changes: 11 additions & 2 deletions readme_examples/2_parallel_map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,18 @@

def p_map(enum)
ch = xchan
enum.map { |e| Process.fork { ch.send yield(e) } }
enum.map
.with_index { |e, i| fork { sleep(e); ch.send yield([e * 2, i]) } }
.each { Process.wait(_1) }
enum.map { ch.recv }
.sort { _1.pop }
.map { _1[0] }
end

p p_map([1,2,3]) { _1 * 2 }
t = Time.now
print p_map([3, 2, 1]) { _1 * 2 }, "\n"
print "Duration: #{Time.now - t}", "\n"

# == Output
# [6, 4, 2]
# Duration: 3.00XXX

0 comments on commit 9d5101c

Please sign in to comment.