The application of mutex lock in python

The background meaning of mutexes

We know that multiple threads under a process can share global variables, but sometimes this will cause a lot of problems. It is possible that two or more threads have grabbed global variables at a certain moment, and execution together may cause problems. Let the data go wrong. At this time, we introduced the concept of mutual exclusion lock. When a thread gets the data, it will be locked immediately. At this time, another thread will not be able to operate this global variable, ensuring the accuracy of the data.
In python, we can implement the code by threading this module as follows:

import threading

#用这个模块下的lock函数
lock = threading.lock()

#上锁代码
lock.acquire()

#释放锁代码
lock.release()

Deadlock

When a thread gets the task and fails to execute the lock release due to an error, then the subsequent threads have been waiting for the task at this time, which causes a deadlock. We can put the release lock code behind some code that may be wrong To solve the deadlock problem

Guess you like

Origin blog.csdn.net/weixin_48445640/article/details/108874857