Skip to content

Instantly share code, notes, and snippets.

@headius
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save headius/252206b478018d71d85b to your computer and use it in GitHub Desktop.
Save headius/252206b478018d71d85b to your computer and use it in GitHub Desktop.
Built-in atomic variables for JRuby...hopefully we can get this into Ruby 2.2

Currently, in order to have atomic operations in Ruby you must use my "atomic" gem. Ideally, we'd have VM-level support for atomic operations on instance variables, to enable us to build higher-level concurrency abstractions efficiently.

See https://bugs.ruby-lang.org/issues/8259 if you'd like to contribute to this effort.

>> class Foo
>> attr_accessor :bar, atomic: true
>> end
=> nil
>> hello, goodbye = 'hello'.freeze, 'goodbye'.freeze
=> ["hello", "goodbye"]
>> f = Foo.new
=> #<Foo:0x32f67bbb>
>> f.bar = hello
=> "hello"
>> f.bar_swap goodbye
=> "hello"
>> f.bar
=> "goodbye"
>> f.bar_cas hello, 'world'
=> false
>> f.bar
=> "goodbye"
>> f.bar_cas goodbye, 'world'
=> true
>> f.bar
=> "world"
@chrisseaton
Copy link

What's the difference between #bar= and #bar_swap here? I see it's distinct from CAS, and there's no expected value passed in.

@chrisseaton
Copy link

I'll answer my own lazy question - it returns the old value, where assignment returns the new value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment