Issue #14706 has been updated by mperham (Mike Perham).


Jeremy, good point.  I would agree that the different semantics are enough to justify a different class.  Namespacing it within the Thread class also seems reasonable, e.g. `Thread::Counter` so it would be available if you `require 'thread'`.

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

* 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:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>