Skip to content

Thread safety and watch/multi/exec? #228

@corasaurus-hex

Description

@corasaurus-hex

I think there's a thread safety issue with watch/multi/exec w/ redis-rb. The following test demonstrates the issue.

test "thread safety with multi and watch" do
  next unless driver == :ruby || driver == :hiredis

  redis = Redis.connect(OPTIONS)
  mutex = Mutex.new
  cvar  = ConditionVariable.new

  redis.set "foo", 1

  # The watch in thread 1 will bleed over into the multi call in thread 2 and be
  # unwatched when the multi call in thread 2 ends. The change that we make to
  # foo in thread 2 should cause the multi in thread 1 to fail, but it doesn't.

  t1 = Thread.new do
    redis.watch "foo"
    mutex.synchronize{ cvar.wait(mutex) }
    redis.multi do |r|
      r.set "foo", 4
    end
  end

  t2 = Thread.new do
    redis.watch "bar"
    sleep 1
    result = redis.multi do |r|
      r.set "bar", 2
    end
    redis.set "foo", 5
    cvar.signal
  end

  t1.join
  t2.join
  assert_equal "5", redis.get("foo")
end

The way I'm forcing it with a condition variable and mutex is contrived, I'll admit, but it's just there to force the issue to be consistent.

Am I using the library wrong, or is this actually an issue? I suppose I could synchronize around the whole thing, or use a connection pool...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions