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)

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 programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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.

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.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles