Comment on this RCR (edit wiki page) | RCRchive home

RCR 269: Add Thread.atomic

submitted by Robert on Tue Aug 03 2004 04:56:20 AM -0700

Status: withdrawn


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

Add comments here

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: http://www.ruby-doc.org/core/classes/Thread.html#M000972

Thanks for that hint, Paul!

Withdrawing RCR...

-- Robert



Vote for this RCR

Strongly opposed [1]
Opposed [0]
Neutral [0]
In favor [1]
Strongly advocate [0]

Change the status of this RCR to:

accepted

rejected

withdrawn


Add comments here

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: http://www.ruby-doc.org/core/classes/Thread.html#M000972

Thanks for that hint, Paul!

Withdrawing RCR...

-- Robert


Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog