ruby picture

RCR 269: Add Thread.atomic

Submitted by Robert (Tue Aug 03 08:08:20 UTC 2004)

Abstract

Provide a method that guarantees that certain code is executed atomic without other threads interfering.

Problem

Many people still use Thread.critical which is error prone (often the idiom begin-ensure-end is not followed). Code will be less susceptible to bugs if there was a method that covered the typical idiom.

Proposal

Add the method atomic to class Thread (see implementation). Additionally if there is time, other places in the std lib that use Thread.critical can be refactored to use the new method.

Analysis

No incompatibilites and only litte impact on performance expected.

Implementation

class Thread
  def self.atomic
    old = critical
    critical = true
    begin
      yield
    ensure
      critical = old
    end
  end
end

ruby picture
Comments Current voting

The implementation has been garbled. So here it is again:

class Thread
  def self.atomic
    old = self.critical
    self.critical = true
    begin
      yield
    ensure
      self.critical = old
    end
  end
end

Guy, thanks for that hint!

-- Robert


I recommend to use Mutex (or Monitor) instead of Thread#critical, which is designed to be an internal kludge to implement mutex etc.

-- matz.


Matz, I couldn't agree more. But apparently there are people who want to use Thread.critical - Thread.atomic could help them to make less errors.

-- Robert


What's wrong with Thread.exclusive { ... } (from thread.rb)?

-- Paul Brannan


Probably that I didn't find it. Documentation seems to be missing:

Thanks for that hint, Paul!

Withdrawing RCR...

-- Robert


Strongly opposed 1
Opposed 0
Neutral 0
In favor 1
Strongly advocate 0
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .