File: counter.rb

package info (click to toggle)
ruby-mongo 2.21.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 14,764 kB
  • sloc: ruby: 108,806; makefile: 5; sh: 2
file content (57 lines) | stat: -rw-r--r-- 1,503 bytes parent folder | download
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
# frozen_string_literal: true

module Mongo
  module DriverBench
    module Parallel
      # An implementation of a counter variable that can be waited on, which
      # will signal when the variable reaches zero.
      #
      # @api private
      class Counter
        # Create a new Counter object with the given initial value.
        #
        # @param [ Integer ] value the starting value of the counter (defaults
        #    to zero).
        def initialize(value = 0)
          @mutex = Thread::Mutex.new
          @condition = Thread::ConditionVariable.new
          @counter = value
        end

        # Describes a block where the counter is incremented before executing
        # it, and decremented afterward.
        #
        # @yield Calls the provided block with no arguments.
        def enter
          inc
          yield
        ensure
          dec
        end

        # Waits for the counter to be zero.
        def wait
          @mutex.synchronize do
            return if @counter.zero?

            @condition.wait(@mutex)
          end
        end

        # Increments the counter.
        def inc
          @mutex.synchronize { @counter += 1 }
        end

        # Decrements the counter. If the counter reaches zero,
        # a signal is sent to any waiting process.
        def dec
          @mutex.synchronize do
            @counter -= 1 if @counter.positive?
            @condition.signal if @counter.zero?
          end
        end
      end
    end
  end
end