skip to Main Content

I am trying to use redis for a simple process.
Process :-
Read value for a key and update it.
Example :- (a,1)
Read a value and update 1 to 2.
The problem here is that in multithreaded environment ,multiple thread (say 4) read at same time and then update it to 2, actually it should have been 4 .Is there a way where in I can impose locking in redis such that if one thread reads a value it imposes a lock so that other threads are kept in waiting state?

2

Answers


  1. Use INCRBY to do an atomic increment:

    redis> SET mykey "10"
    "OK"
    redis> INCRBY mykey 5
    (integer) 15
    redis> 
    

    Or, if you need something more sophisticated, use an uninterruptible MULTI command.

    Login or Signup to reply.
  2. you do not need the lock. In multithreaded environment, suppose 4, they send
    read and update commands to Redis not in right order.
    may be:

    1:read->2:read->1:update->2:update->3:read->3:update->4:read->4:update

    you need combine 1:read and 1:update to an atomic operation, that is Lua Script.

    you can write a Lua script for all operation and execute it whit EVAL command, the multithreaded commands will in right order.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search