[ruby-core:86659] [Ruby trunk Feature#14706] Atomic Integer incr/decr

From: merch-redmine@...
Date: 2018-04-23 21:18:48 UTC
List: ruby-core #86659
Issue #14706 has been updated by jeremyevans0 (Jeremy Evans).


I think this feature in general is a good candidate for addition to stdlib.

I don't think the `Integer` class is appropriate for this, because (some) Integers are immediate values, and all Integers are frozen, and you can't modify them.  `Integer#+` and `Integer#succ` are thread safe (they return new objects, they do not modify existing objects), it's `counter += 1` that is not thread safe.

In terms of naming, maybe `Integer::Counter` since that is unlikely to conflict with existing code, with an API like:

~~~ ruby
counter = Integer::Counter.new(0) # maybe default to 0 if no argument?
counter.incr     # => 1
counter.incr(10) # => 11
counter.incr(-1) # => 10
counter.reset    # => 10
counter.to_int   # => 0
counter.to_i     # => 0
~~~


 

----------------------------------------
Feature #14706: Atomic Integer incr/decr
https://bugs.ruby-lang.org/issues/14706#change-71616

* Author: mperham (Mike Perham)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
Ruby does not any thread-safe way to implement simple counters without a Mutex.  Today Ruby provides Integer#succ but this funcalls "+", making it thread-unsafe as far as I know.

I'd propose adding Integer#incr(amount=1) and Integer#reset which would use atomic operations, giving us thread-safe, high-performance counters.

~~~ ruby
counter = 0
counter.incr # => 1
counter.incr(10) # => 11
counter.incr(-1) # => 10
counter.reset # => 10
counter # => 0
~~~




-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>

In This Thread

Prev Next