damoiser
damoiser

Reputation: 6238

Rails concurrence issue - how to use locks

I have a lib class ("Updater") that do some long tasks, this tasks can be launched manually (in the browser) or every 2 hours (I have implemented whenever gem, that does a schedule every 2 hours of this task).

Seen that this tasks make a lot of work on the DB, I think that some concurrence errors can occurs (if for example calling when is yet working). Have I right?

I have thought a solution with mutex, having a pseudo code for my Updater class like this:

module Updater
  def start
    #do some job
  end
end

A correct solution, I think, is something like this

module Updater
  def start
    mutex.lock
       #do some job
    mutex.unlock
  end
end

Is my solution correct?

Can please provide some more informations about concurrence (for example how to use correctly mutex in Rails, what I must require, etc..)? I have searched but found nothing with good explanation.

Upvotes: 0

Views: 1230

Answers (1)

0x4a6f4672
0x4a6f4672

Reputation: 28245

I think the correct way to use a Ruby Mutex is obtain a lock, run a code block, and then release the lock again, i.e. to call lock in combination with unlock...

@mutex = Mutex.new
..

def start
  @mutex.lock
  begin
    ..
  ensure
    @mutex.unlock rescue nil
  end
end

or to use the synchronize method:

@mutex = Mutex.new
..

def start
  @mutex.synchronize do
    # do something
  end
end

An example can be found in the Rack Middleware class Rack::Lock. But I am not sure if it helps in your case, even if you use class variables like @@mutex, because the mutex/semaphore may not be preserved between different tasks and distinct processes (I assume that the "tasks" are different processes started by "rake tasks"). The Mutex class is useful to achieve thread safety, since it implements a simple semaphore that can be used to coordinate access to shared data from multiple concurrent threads. However, there is also a nice RailsCast about Thread-Safety (unfortunately only behind a paywall).

In your case it may help to create a global lock flag in the database, or to create a global lock file in the filesystem with touch lock.txt and to remove it again with rm lock.txt when the process is over. It is possible to execute these shell commands in Ruby with Kernel.system or %x. If the file exists File.exists?("lock.txt") then the update can be suspended.

Upvotes: 1

Related Questions