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
Use
INCRBY
to do an atomic increment:Or, if you need something more sophisticated, use an uninterruptible MULTI command.
you do not need the lock. In multithreaded environment, suppose 4, they send
read
andupdate
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.