Detailed explanation of synchronization lock in python thread
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()
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()
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()
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()
相关推荐:
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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


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

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.