[ruby-core:77966] [Ruby trunk Bug#12607] Ruby needs an atomic integer
From:
ko1@...
Date:
2016-11-05 10:00:43 UTC
List:
ruby-core #77966
Issue #12607 has been updated by Koichi Sasada.
At first, we need a box of integer, not an atomic integer.
Like that:
```ruby
box = IntegerBox.new(0)
box.increment
box.increment
box.to_i #=> 2
```
This IntegerBox can be implemented by the following code:
```ruby
class IntegerBox
def initialize n
@n = n
@m = Mutex.new
end
def increment i = 1
@m.synchonization{ @n += i }
end
def to_i
@n
end
end
```
I'm not sure such small part should be include in Ruby's core library.
BTW, concurrent-ruby supports AtomicFixnum <http://ruby-concurrency.github.io/concurrent-ruby/Concurrent/AtomicFixnum.html>.
```
af = Concurrent::AtomicFixnum.new(0)
af.increment
af.increment
af.value #=> 2
```
It has `update` method to set new value. It seems useful.
```
v = af.value
new_v = v + 5
af.update{ new_v }
```
But this small code doesn't work as intended.
This is why I think thread-programming is not easy, even if there is cool threading tools.
----------------------------------------
Bug #12607: Ruby needs an atomic integer
https://bugs.ruby-lang.org/issues/12607#change-61298
* Author: Shyouhei Urabe
* Status: Assigned
* Priority: Normal
* Assignee: Koichi Sasada
* ruby -v:
* Backport: 2.1: UNKNOWN, 2.2: UNKNOWN, 2.3: UNKNOWN
----------------------------------------
(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>