In fact, it is not appropriate to modify data with multiple threads. After all, the redis server is single-threaded and all commands are executed serially. It is only when the client sends commands concurrently that it causes serialization. Some command arrangement issues and network time differences cause data inconsistency. Although this article is about the addition and subtraction of numbers, in order to illustrate the lock situation, the atomic command incr is not intentionally used. (Recommended: redis video tutorial)
First add a simple RedisHelper, a set value, a get value, and a set concurrent lock, so that in my subsequent operations, you can Know exactly what I did.
public class RedisHelper { public RedisClient client = new RedisClient("127.0.0.1", 6379); public void Set<T>(string key, T val) { client.Set(key, val); } public T Get<T>(string key) { var result = client.Get<T>(key); return result; } public IDisposable Acquire(string key) { return client.AcquireLock(key); } }
Looking at the concurrent code below, I only added two new Threads. Two threads want to access the same key at the same time, each accessing 50,000 times. Under concurrent conditions, it is difficult for us to ensure the accuracy of the data. Please compare the output results.
static void Main(string[] args) { RedisHelper rds = new RedisHelper(); rds.Set<int>("mykey1", 0); Thread myThread1 = new Thread(AddVal); Thread myThread2 = new Thread(AddVal); myThread1.Start(); myThread2.Start(); Console.WriteLine("等待两个线程结束"); Console.ReadKey(); } public static void AddVal() { RedisHelper rds = new RedisHelper(); for (int i = 0; i < 50000; i++) { int result = rds.Get<int>("mykey1"); rds.Set<int>("mykey1", result + 1); } Console.WriteLine("线程结束,输出" + rds.Get<int>("mykey1")); }
Yes, with our single thread, running two 50000 will output 100000. Now two concurrent threads are running at the same time. Due to concurrency, the data results are often not what we want. So how to solve this problem, Redis is already ready for us!
You can see that one of the methods in my RedisHelper is public IDisposable Acquire(string key). You can also see that it returns IDisposable, which proves that we need to manually release resources.
The AcquireLock inside the method is the key point. It is like asking for a lock in redis. The locked resource can only be accessed by a single thread and will not be get or set by two threads at the same time. These two threads must be carried out alternately. Of course, the alternation here does not mean once for you and once for me. It may also be for you multiple times and once for me. See the code below.
static void Main(string[] args) { RedisHelper rds = new RedisHelper(); rds.Set<int>("mykey1", 0); Thread myThread1 = new Thread(AddVal); Thread myThread2 = new Thread(AddVal); myThread1.Start(); myThread2.Start(); Console.WriteLine("等待两个线程结束"); Console.ReadKey(); } public static void AddVal() { RedisHelper rds = new RedisHelper(); for (int i = 0; i < 50000; i++) { using (rds.Acquire("lock")) { int result = rds.Get<int>("mykey1"); rds.Set<int>("mykey1", result + 1); } } Console.WriteLine("线程结束,输出" + rds.Get<int>("mykey1")); }
You can see that I used using to call my Acquire method to acquire the lock.
The final output result is 100000, which is the correct result we want. The previous 8W is because one of the two threads ended execution first.
Also, during the official use process, it is recommended to delete the lock given to us after use, and add an expiration time, using expire.
To avoid unexpected exit during program execution, the lock will always exist and the locked data may not be updated or obtained in the future.
You can also try not to set expire. When the program just starts executing, close the console, re-run the program, and get the value you locked in the redis-cli operation console, and it will be obtained forever. Less than.
All machines connected to this redis instance can only have one lock that acquires the specified name at the same time.
The following is how StackExchange.Redis is written
var info = "name-"+Environment.MachineName; //如果5秒不释放锁 自动释放。避免死锁 if (db.LockTake("name", info, TimeSpan.FromSeconds(5))) { try { } catch (Exception ex) { } finally { db.LockRelease("name", token); } }
More redis For knowledge, please pay attention to the redis database tutorial column.
The above is the detailed content of Simple application introduction of Redis lock. For more information, please follow other related articles on the PHP Chinese website!

Redis是现在最热门的key-value数据库,Redis的最大特点是key-value存储所带来的简单和高性能;相较于MongoDB和Redis,晚一年发布的ES可能知名度要低一些,ES的特点是搜索,ES是围绕搜索设计的。

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于redis的一些优势和特点,Redis 是一个开源的使用ANSI C语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式存储数据库,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis Cluster集群收缩主从节点的相关问题,包括了Cluster集群收缩概念、将6390主节点从集群中收缩、验证数据迁移过程是否导致数据异常等,希望对大家有帮助。

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,希望对大家有帮助。

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于原子操作中命令原子性的相关问题,包括了处理并发的方案、编程模型、多IO线程以及单命令的相关内容,下面一起看一下,希望对大家有帮助。

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了bitmap问题,Redis 为我们提供了位图这一数据结构,位图数据结构其实并不是一个全新的玩意,我们可以简单的认为就是个数组,只是里面的内容只能为0或1而已,希望对大家有帮助。

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于实现秒杀的相关内容,包括了秒杀逻辑、存在的链接超时、超卖和库存遗留的问题,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
