当前位置:网站首页>Strategies for common locks in multithreading
Strategies for common locks in multithreading
2022-07-27 06:15:00 【Envy only mandarin ducks, not immortals】
Catalog
One 、 Common lock strategies for multithreading
1、 Optimistic lock and pessimistic lock
(1) Explanation of optimistic lock
(2) Explanation of pessimistic lock
(3) Examples of two strategies
(4) Optimistic lock detects data conflicts
(1) Introduction to read-write lock
3、 Heavyweight locks and lightweight locks
One 、 Common lock strategies for multithreading
1、 Optimistic lock and pessimistic lock
(1) Explanation of optimistic lock
It is assumed that data generally does not produce concurrency conflicts , So when the data is submitted for update , Will formally determine whether the data is generated and Send conflict detection , If concurrency conflicts are found , Returns the user's error message , Let the user decide how to do it .
(2) Explanation of pessimistic lock
Always assume the worst , Every time I go to get the data, I think others will modify it , So every time I get the data, I lock it , So people who want to take this data will block it until it gets the lock .
(3) Examples of two strategies

When the thread conflict is not serious , Optimistic locking strategy can be adopted to avoid multiple lock adding and lock releasing operations
When thread conflicts are serious , Pessimistic locking can be used to prevent threads from frequently accessing shared data CPU Idling problem
(4) Optimistic lock detects data conflicts
Optimistic locking does not really block threads , The implementation of optimistic locking can introduce “ Version number ” To solve the problem


The thread 2 Operation strategy of :
● Direct error , Threads 2 sign out , If you don't write to the main memory
● Read and write the latest value from main memory 50 And version number 2, And then execute it again -20 operation =30, Then write it back to the main memory
The core of the above illustration is , Whether the thread can successfully refresh the value of main memory depends on
Version number in working memory == The version number in the main memory can be updated , After the update is successful , Synchronously refresh your version number and the version number of main memory , That is, the update is successful
2、 Read-write lock
(1) Introduction to read-write lock
Between threads , There is no thread safety problem between data readers , But the writers of the data need to communicate with each other and with the readers To be mutually exclusive . If the same lock is used in both scenarios , There will be great performance loss . Therefore, read-write locks are generated .
Read-write lock (readers-writer lock), Look at English, as the name suggests , When performing the lock operation, it is necessary to indicate the read-write intent additionally , Readers are not mutually exclusive , The writer requires mutual exclusion from anyone .
A thread's access to data , There are two main operations :
● Reading data and Writing data .
● Both threads just read one data , There is no thread safety issue at this time . Read directly and concurrently .
● Both threads have to write a data , There are thread safety issues , Only one thread can obtain a write lock , Other threads are blocked
● One thread reads and another thread writes , There are also thread safety issues , When the write thread ends, the read thread can continue
Read / write locks are mostly used for threads that are basically reading data , Write less data
(2)java Read write lock in
Read write lock is to distinguish between read operation and write operation .
Java The standard library provides ReentrantReadWriteLock class , Realize the read-write lock . ●ReentrantReadWriteLock.ReadLock Class represents a read lock . This object provides lock / unlock methods Lock and unlock .
●ReentrantReadWriteLock.WriteLock Class represents a write lock . This object also provides lock / unlock Method to lock and unlock .
among , Between read lock and read lock , Not mutually exclusive . Between write lock and write lock , Mutually exclusive . Between read lock and write lock , Mutually exclusive .
3、 Heavyweight locks and lightweight locks
(1) Heavyweight lock
Need the support of operating system and hardware , The thread obtains the heavyweight lock and enters the blocking state ( Dependent operating system , Frequently switch between user mode and kernel mode , Very expensive ).
If you go to the bank to handle business , User mode is to handle business by yourself outside the window , The kernel mode requires staff to assist in handling business in the window , When a business needs to switch frequently between user mode and kernel mode ( That is, they keep running around between the external window and the staff , It will be very time-consuming )
(2) Lightweight lock
Try to perform operations in user mode , Threads don't block , No state switching
Let's say when we deal with business in the bank , The current business can be processed in an external window , There is no need to run back and forth , You can save a lot of time , Save money .
4、 spinlocks
The common implementation of lightweight lock is spin lock
As before , The thread enters the blocking state after the lock grabbing failure , give up CPU, It will take a long time to be scheduled again . But actually , In most cases , Although the current lock grab failed , But it won't be long , The lock will be released . There's no need to give up CPU. This Spin lock can be used to deal with such problems .
while ( Grab the lock (lock) == Failure ) {}If the lock acquisition fails , Try to get the lock again now , Infinite loop , Until we get the lock . Failed to acquire lock for the first time , The second attempt will come in a very short time . Once the lock is released by another thread , You can get the lock at the first time .
5、 Fair and non-fair locks
Fair lock : comply with " first come , first served ". B Than C First come . When A After releasing the lock , B Before C Get lock .
Not fair lock : Non compliance " first come , first served ". B and C It's possible to get the lock .

边栏推荐
猜你喜欢

UnityShader-深度纹理(理解以及遇到的问题)

Leetcode one question per day 30. Concatenate substrings of all words

所有常用排序的代码实现和介绍

Code implementation and introduction of all commonly used sorting

The principle of hash table and the solution of hash conflict

PZK学C语言之初识指针

Remote sensing image recognition training strategy

非真实感渲染(NPR)论文理解及其复现(Unity) - 《Stylized Highlights for Cartoon Rendering and Animation》

Unity hub login no response

软件测试基础概念篇
随机推荐
[dynamic planning - steel bar cutting]
Remote sensing image recognition training strategy
力扣题解 动态规划(7)
wireshark数据包修改--IP地址修改(一)
【动态规划----钢条切割问题】
C语言扫雷最新 递归展开 超详解(附源码)
Summary of the use of C # Jason code in TCP communication
Leetcode one question per day 30. Concatenate substrings of all words
Remote sensing image recognition - making data sets
Li Kou 236. the nearest common ancestor of binary tree
力扣题解 二叉树(6)
基于C#的Winform对Access数据库进行操作(mdb结尾)
Acwing the number of square arrays of one question per day
Thesis writing (harvest)
力扣题解 动态规划(5)
人月神话阅读笔记
ROS运行管理之launch文件
C#文件的读写
Dynamic planning for solving problems (4)
编程学习记录——第3课【初识C语言】