Home Backend Development Python Tutorial Detailed explanation of synchronization lock in python thread

Detailed explanation of synchronization lock in python thread

Apr 27, 2018 am 10:01 AM
python thread Detailed explanation

This article mainly introduces the relevant information of synchronization locks in python threads in detail, which has certain reference value. Interested friends can refer to it

In applications using multi-threads, How to ensure thread safety, synchronization between threads, or access to shared variables are very difficult issues. They are also problems faced when using multi-threading. If not handled well, it will bring serious consequences. Use python multi-threading. Lock Rlock Semaphore Event Condition is provided to ensure synchronization between threads, and the latter ensures mutual exclusion of access to shared variables

Lock & RLock: Mutex locks are used to ensure multi-thread access to shared variables
Semaphore object: An enhanced version of the Lock mutex, which can be owned by multiple threads at the same time, while Lock can only be owned by a certain thread at the same time.
Event object: It is a method of communication between threads, equivalent to a signal. One thread can send a signal to another thread and then let it perform an operation.
Condition object: It can process data only after certain events are triggered or specific conditions are met

1. Lock (mutex lock)

Request lock — Enter the lock pool and wait — Acquire lock — Locked — Release lock

Lock (instruction lock) is the lowest-level synchronization instruction available. When Lock is in the locked state, it is not owned by a specific thread. Lock contains two states - locked and non-locked, and two basic methods.

It can be thought that Lock has a lock pool. When a thread requests a lock, the thread is placed in the pool until it is released from the pool after obtaining the lock. Threads in the pool are in the synchronous blocking state in the state diagram.

Construction method:
Lock()

Instance method:
acquire([timeout]): Put the thread into a synchronous blocking state and try to obtain the lock .
release(): Release the lock. The thread must have acquired the lock before use, otherwise an exception will be thrown.

if mutex.acquire():
 counter += 1
 print "I am %s, set counter:%s" % (self.name, counter)
  mutex.release()
Copy after login

2. RLock (reentrant lock)

RLock (reentrant lock) is a Synchronization instructions requested multiple times by the same thread. RLock uses the concepts of "owned thread" and "recursion level". When in the locked state, RLock is owned by a thread. The thread that owns the RLock can call acquire() again and needs to call release() the same number of times to release the lock.

It can be considered that RLock contains a lock pool and a counter with an initial value of 0. Each time acquire()/release() is successfully called, the counter will be 1/-1. When it is 0, the lock is in the unlocked state. Locked status.

Construction method:
RLock()

Instance method:
acquire([timeout])/release(): Similar to Lock.

3. Semaphore (shared object access)

Let’s talk about Semaphore again. To be honest, Semaphore is the latest synchronization lock I used. Similar implementations in the past were I used Rlock to implement it, which is relatively convoluted. After all, Rlock requires locking and unlocking in pairs. . .

Semaphore manages a built-in counter,
The built-in counter is -1 whenever acquire() is called;
The built-in counter is 1 when release() is called;
The counter cannot be less than 0; when the counter When 0, acquire() will block the thread until another thread calls release().

Go directly to the code, we control the semaphore to 3, that is to say, 3 threads can use this lock at the same time, and the remaining threads can only block and wait...

#coding:utf-8
#blog xiaorui.cc
import time
import threading

semaphore = threading.Semaphore(3)

def func():
 if semaphore.acquire():
  for i in range(3):
   time.sleep(1)
   print (threading.currentThread().getName() + '获取锁')
  semaphore.release()
  print (threading.currentThread().getName() + ' 释放锁')


for i in range(5):
 t1 = threading.Thread(target=func)
 t1.start()
Copy after login

4. Event (inter-thread communication)

Event contains a flag internally, which is initially false.
You can use set() to set it to true;
Or use clear() to reset it to false;
You can use is_set() to check the status of the flag bit;

Another most important function is wait(timeout=None), which is used to block the current thread until the internal flag bit of the event is set to true or the timeout times out. If the internal flag is true, the wait() function understands and returns.

import threading
import time

class MyThread(threading.Thread):
 def __init__(self, signal):
  threading.Thread.__init__(self)
  self.singal = signal

 def run(self):
  print "I am %s,I will sleep ..."%self.name
  self.singal.wait()
  print "I am %s, I awake..." %self.name

if __name__ == "__main__":
 singal = threading.Event()
 for t in range(0, 3):
  thread = MyThread(singal)
  thread.start()

 print "main thread sleep 3 seconds... "
 time.sleep(3)

 singal.set()
Copy after login

5. Condition (thread synchronization)

Condition can be understood as an advanced tool. Provides more advanced functions than Lock and RLock, allowing us to control complex thread synchronization issues. threadiong.Condition maintains a threadion object internally (the default is RLock), which can be passed in as a parameter when creating a Condigtion object. Condition also provides acquire and release methods, whose meanings are consistent with the acquire and release methods of the host. In fact, they just simply call the corresponding methods of the internal host object. Condition also provides the following methods (especially note: these methods can only be called after acquiring, otherwise a RuntimeError exception will be reported.):

Condition.wait([ timeout]):

wait method releases the internal occupied thread, and the thread is suspended until it is awakened after receiving a notification or times out (if the timeout parameter is provided) . When the thread is awakened and reoccupies the thread, the program will continue to execute.

Condition.notify():

Wake up a suspended thread (if there is a suspended thread). Note: The notify() method will not release the occupied memory.

Condition.notify_all()
Condition.notifyAll()

唤醒所有挂起的线程(如果存在挂起的线程)。注意:这些方法不会释放所占用的琐。

对于Condition有个例子,大家可以观摩下。

from threading import Thread, Condition
import time
import random

queue = []
MAX_NUM = 10
condition = Condition()

class ProducerThread(Thread):
 def run(self):
  nums = range(5)
  global queue
  while True:
   condition.acquire()
   if len(queue) == MAX_NUM:
    print "Queue full, producer is waiting"
    condition.wait()
    print "Space in queue, Consumer notified the producer"
   num = random.choice(nums)
   queue.append(num)
   print "Produced", num
   condition.notify()
   condition.release()
   time.sleep(random.random())


class ConsumerThread(Thread):
 def run(self):
  global queue
  while True:
   condition.acquire()
   if not queue:
    print "Nothing in queue, consumer is waiting"
    condition.wait()
    print "Producer added something to queue and notified the consumer"
   num = queue.pop(0)
   print "Consumed", num
   condition.notify()
   condition.release()
   time.sleep(random.random())


ProducerThread().start()
ConsumerThread().start()
Copy after login

相关推荐:

python多线程之事件Event的使用详解

python线程池threadpool的实现

The above is the detailed content of Detailed explanation of synchronization lock in python thread. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles