How to block a set of objects for an operation?

In my rails application, I have code like this:

def foo
  if object_bar_exists
    raise "can't create bar twice!"
  end

  Bar.create
end

which can be caused by two different requests coming to the application server. If this code is launched by two requests at the same time, and both of them simultaneously run the test if, then the other bar2 will not be found bar.

What is the best way to create a mutex for a collection of bars? Table of special purpose mutexes in the database?

Update

I must emphasize that I cannot use the memory mutex here, because concurrency occurs through requests / processes, not threads.

+5
source share
3

. , , , , , , Mutex , . , :

ActiveRecord::Base.transaction do
  # Transaction code goes here.
end

, Bar, :

ActiveRecord::Base.transaction do
  bar = Bar.new(params[:bar])
  bar.save!
end

bar , :

ActiveRecord::Base.transaction do
  bar = Bar.find(1, :lock => true)
  # perform operations on bar
end
+4

, Ruby, Mutex: Mutex Docs.

rvms, / Bar, , db -.

+1

, , Singleton lib, , .

, . , , - .

For several computers, you will need to store the token in the database and synchronize some access to the token. For example, a token must be requested and pulled out, and keep track of some number or something so that people cannot simultaneously remove the token. Or use a centralized web service lock so that your token processing is only in one place.

0
source

All Articles