semaphore 0.0.1

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/semaphore.rb +63 -0
  2. metadata +47 -0
@@ -0,0 +1,63 @@
1
+ #
2
+ # semaphore.rb
3
+ # Counting semaphore implementation for Ruby 1.9.3
4
+ # Version: 0.0.1
5
+ # Author: Luis Doubrava, Rob van Aarle
6
+ # Based on semaphore.rb,v 1.2 2003/03/15 20:10:10 fukumoto Exp
7
+ #
8
+
9
+ class CountingSemaphore
10
+ def initialize(initvalue = 0)
11
+ @counter = initvalue
12
+ @waiting_thread = nil
13
+ @counter_mutex = Mutex.new
14
+ @queue_mutex = Mutex.new
15
+ end
16
+
17
+ def wait
18
+ @queue_mutex.synchronize do
19
+ stop_thread = false
20
+ @counter_mutex.synchronize do
21
+ if (@counter -= 1) < 0
22
+ @waiting_thread = Thread.current
23
+ stop_thread = true
24
+ end
25
+ self
26
+ end
27
+ Thread.stop if stop_thread
28
+ end
29
+ end
30
+
31
+ def signal
32
+ @counter_mutex.synchronize do
33
+ begin
34
+ if (@counter += 1) <= 0
35
+ if @waiting_thread
36
+ @waiting_thread.wakeup
37
+ @waiting_thread = nil
38
+ end
39
+ end
40
+ rescue ThreadError
41
+ retry
42
+ end
43
+ self
44
+ end
45
+ end
46
+
47
+ alias down wait
48
+ alias up signal
49
+ alias P wait
50
+ alias V signal
51
+
52
+ def exclusive
53
+ wait
54
+ yield
55
+ ensure
56
+ signal
57
+ end
58
+
59
+ alias synchronize exclusive
60
+
61
+ end
62
+
63
+ Semaphore = CountingSemaphore
metadata ADDED
@@ -0,0 +1,47 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: semaphore
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Luis Doubrava
9
+ - Rob van Aarle
10
+ autorequire:
11
+ bindir: bin
12
+ cert_chain: []
13
+ date: 2012-08-02 00:00:00.000000000 Z
14
+ dependencies: []
15
+ description: ! 'Counting semaphore implementation for Ruby 1.9.3 based on semaphore.rb,v
16
+ 1.2 2003/03/15 20:10:10 by Fukumoto. '
17
+ email: ldoubrava@cg.nl
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - lib/semaphore.rb
23
+ homepage: http://rubygems.org/gems/semaphore
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: '0'
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.24
44
+ signing_key:
45
+ specification_version: 3
46
+ summary: Counting semaphore implementation for Ruby 1.9.3
47
+ test_files: []