There is an asynchronous problem in redis

If redis is the only thread server, why is the result not 100,000? I think this is not a redis problem, but I want to know the reason. Thank.

        RedisConnection.Default.Database.StringSet("mykey1", 0);
        Parallel.For(0, 50000, new ParallelOptions { MaxDegreeOfParallelism = 2 }, (i) =>
        {
            var number = RedisConnection.Default.Database.StringGet("mykey1");
            int result = int.Parse(number);
            RedisConnection.Default.Database.StringSet("mykey1", result + 1);

        });
        Console.WriteLine("Result" + RedisConnection.Default.Database.StringGet("mykey1"));
+4
source share
2 answers

You can use MULTI / EXEC to avoid this problem. He will ensure that the two teams are not separated by another team. It will be a transaction.

+1
source

As you make two separate calls Redis, without the use of transaction block (MULTI / EXEC) your operations StringGetand StringSetare not atomic. Running threads can alternate between Get and Set operations.

Think of one possible execution sequence:

  • Thread1 Reads myKey1 = 40
  • Thread2 myKey1 = 40
  • Thread2 myKey 41
  • Thread2 myKey1 = 41
  • Thread2 myKey 42
  • Thread1 myKey1 41

, StringGet StringSet StringIncrement:

    RedisConnection.Default.Database.StringSet("mykey1", 0);
    Parallel.For(0, 50000, new ParallelOptions { MaxDegreeOfParallelism = 2 }, (i) =>
    {
        RedisConnection.Default.Database. StringIncrement("mykey1");
    });
    Console.WriteLine("Result" + RedisConnection.Default.Database.StringGet("mykey1"));
0

Source: https://habr.com/ru/post/1684799/


All Articles