barrier 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (2) hide show
  1. data/lib/barrier.rb +47 -0
  2. metadata +47 -0
@@ -0,0 +1,47 @@
1
+ require 'thread'
2
+
3
+ # A synchronization barrier enables multiple threads to wait until all threads
4
+ # have all reached a particular point of execution before any thread
5
+ # continues.
6
+ class Barrier
7
+
8
+ # Initialize new barrier. The _count_ argument specifies the number of threads
9
+ # that must call #wait before any of them successfully return from the call.
10
+ # The value specified by _count_ must be greater than zero.
11
+ #
12
+ # For example
13
+ # b = Barrier.new(3)
14
+ # 3.times do
15
+ # Thread.new do
16
+ # print 1
17
+ # b.wait
18
+ # print 2
19
+ # end
20
+ # end
21
+ # sleep(1)
22
+ # puts
23
+ # produce
24
+ # 111222
25
+ def initialize(count)
26
+ @count_max = count
27
+ @count = 1
28
+ @mutex = Mutex.new
29
+ @lock = ConditionVariable.new
30
+ end
31
+
32
+ # The #wait function shall synchronize participating threads at the barrier.
33
+ # The calling thread shall block until the required number of threads have
34
+ # called #wait specifying the barrier.
35
+ def wait
36
+ @mutex.synchronize do
37
+ if @count < @count_max
38
+ @count += 1
39
+ @lock.wait(@mutex)
40
+ else
41
+ @count = 1
42
+ @lock.broadcast
43
+ end
44
+ end
45
+ nil
46
+ end
47
+ end
metadata ADDED
@@ -0,0 +1,47 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: barrier
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Aleksey Vereshchagin
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-04-26 00:00:00.000000000 Z
13
+ dependencies: []
14
+ description: ! " A synchronization barrier enables multiple threads to wait until
15
+ all threads\n have all reached a particular point of execution before any thread\n
16
+ \ continues.\n"
17
+ email: alexeyv.90@gmail.com
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - lib/barrier.rb
23
+ homepage: http://rubygems.org/gems/barrier
24
+ licenses: []
25
+ post_install_message:
26
+ rdoc_options: []
27
+ require_paths:
28
+ - lib
29
+ required_ruby_version: !ruby/object:Gem::Requirement
30
+ none: false
31
+ requirements:
32
+ - - ! '>='
33
+ - !ruby/object:Gem::Version
34
+ version: 1.8.6
35
+ required_rubygems_version: !ruby/object:Gem::Requirement
36
+ none: false
37
+ requirements:
38
+ - - ! '>='
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ requirements: []
42
+ rubyforge_project:
43
+ rubygems_version: 1.8.11
44
+ signing_key:
45
+ specification_version: 3
46
+ summary: A barrier for threads synchronization
47
+ test_files: []