[ruby-core:102095] [Ruby master Feature#12607] Ruby needs an atomic integer
From:
daniel@...42.com
Date:
2021-01-14 14:43:10 UTC
List:
ruby-core #102095
Issue #12607 has been updated by Dan0042 (Daniel DeLorme).
Eregon (Benoit Daloze) wrote in #note-34:
> And how do you implement that efficiently, and in a way that's thread-safe?
> To be clear, Enumerator.new {} is not efficient, so a generator is not good enough, and Fibers can't be resumed across threads.
By "a generator" I did not mean the `Enumerator::Generator` class. I meant a new generator-type class (say, `AtomicSequence`) that is implemented with atomic CAS operations. No one here is disputing the usefulness of atomic integers _in general_, just their relevance as a concurrency primitive in _ruby core_.
A naive implementation of a monotonic sequence using an atomic integer class might look like this:
```ruby
SEQUENCE.increment
guid = SEQUENCE.to_i
```
oops, wrong! When running concurrently this will produce duplicate guids. The correct usage would be `guid = SEQUENCE.increment` but you have to depend on the developer to understand the gotcha with `SEQUENCE.to_i`. In comparison, `guid = SEQUENCE.next` is always correct; you don't even need to be _aware_ of concurrency issues.
What about a naive implementation of metrics/statistics using an atomic integer class...
```ruby
t0 = Time.now
yield
t = ((Time.now - t0) * 1000000).round #microsecond
TIME.increment(t)
NB.increment(1)
avg = TIME.to_i / NB.to_i
```
oops, wrong again! When running concurrently the `avg` might be incorrect.
Maybe a more useful abstraction might be an `AtomicVector`? If such a thing is possible...
```ruby
TIME_NB = AtomicVector.new(0, 0)
TIME_NB.increment(t, 1)
avg = TIME_NB.to_a.inject(:/)
```
Basically all I'm trying to say is there's a clear benefit to choosing abstractions that produce the correct result _even when used naively_. Like Ractor. So I understand why ko1 is reluctant about this.
----------------------------------------
Feature #12607: Ruby needs an atomic integer
https://bugs.ruby-lang.org/issues/12607#change-89952
* Author: shyouhei (Shyouhei Urabe)
* Status: Feedback
* Priority: Normal
* Assignee: ko1 (Koichi Sasada)
----------------------------------------
(This one was derived from bug #12463)
Although I don't think += would become atomic, at the same time I understand Rodrigo's needs of _easier_ counter variable that resists inter-thread tampering. I don't think ruby's Integer class can be used for that purpose for reasons (mainly because it is not designed with threads in mind). Rather we should introduce a integer class which is carefully designed.
Why not import Concurrent::AtomicFixnum into core?
--
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>