Preface
In Python,Lockyesthreading
andmultiprocessing
The synchronization mechanism provided by the module is used to prevent multiple threads or processes from accessing shared resources at the same time, thereby avoiding data competition and inconsistency.
1. () (thread lock)
Used inMulti-threadedIn the environment, prevent multiple threads from accessing shared resources at the same time.
Example: Multiple threads access shared variables
import threading import time counter = 0 # Shared variableslock = () # Create a lock def worker(n): global counter with lock: # Obtain the lock local_counter = counter (0.1) # Simulate some calculations counter = local_counter + n print(f"Thread {threading.current_thread().name} updated counter to {counter}") # Create multiple threadsthreads = [(target=worker, args=(1,)) for _ in range(5)] # Start the threadfor t in threads: () # Wait for all threads to completefor t in threads: () print("Final counter value:", counter)
() Working mechanism
-
()
: Acquire the lock (blocks if the lock has been occupied) -
()
: Release the lock (make it available to other threads) -
with lock:
: recommendHow to usewith
The statement ensures that the lock is automatically released when exiting the code block, even if an exception occurs.
2. () (process lock)
ForMulti-processEnvironment, prevent multiple processes from accessing shared resources at the same time.
Example: Multiple processes access shared resources
import multiprocessing import time counter = ('i', 0) # Shared variableslock = () # Process lock def worker(n): with lock: # Obtain the lock local_counter = (0.1) # Simulate some calculations = local_counter + n print(f"Process {multiprocessing.current_process().name} updated counter to {}") # Create multiple processesprocesses = [(target=worker, args=(1,)) for _ in range(5)] # Start the processfor p in processes: () # Wait for all processes to completefor p in processes: () print("Final counter value:", )
() Working mechanism
-
()
and()
The interface is the same, but it acts between processes. -
with lock:
Ensure that processes are mutually exclusive to access shared resources, prevent data inconsistency.
3. RLock() (reenter lock)
Suitable for recursive calls or for multiple acquisitions of locks on the same thread
import threading lock = () def recursive_function(n): if n <= 0: return with lock: # Allow the same thread to acquire locks multiple times print(f"Acquired lock in recursion level {n}") recursive_function(n - 1) recursive_function(3)
Ordinary Lock cannot be acquired() multiple times by the same thread, but RLock() can!
4. Semaphore() (semaphore)
ForLimit the number of threads/processes to be accessed concurrently(For example: database connection pool).
import threading import time semaphore = (3) # Up to 3 threads are allowed to run simultaneously def worker(n): with semaphore: print(f"Thread {n} is running") (2) print(f"Thread {n} finished") threads = [(target=worker, args=(i,)) for i in range(6)] for t in threads: () for t in threads: ()
- set up
Semaphore(3)
, most3Threads can enter at the same time. - Commonly used in connection pooling, resource management, concurrency restriction and other scenarios.
5. Condition() (condition variable)
For between threadscoordination, for example, one thread needs to wait for another thread to complete an operation before continuing.
import threading condition = () shared_data = None def consumer(): global shared_data with condition: print("Consumer waiting...") () # Wait for producer notification print(f"Consumer received: {shared_data}") def producer(): global shared_data with condition: shared_data = "Data ready!" print("Producer produced data, notifying consumer...") () # Notify consumers t1 = (target=consumer) t2 = (target=producer) () () () ()
Use Condition() to solve the "producer-consumer" problem.
6. Event() (event)
Between threadsSimple signaling mechanism(equivalent to global flag)
import threading import time event = () def worker(): print("Worker waiting for event...") () # Wait for the event to be set print("Worker received event signal!") def set_event(): (3) () # Trigger event (target=worker).start() (target=set_event).start()
Applicable to:
- Synchronization between threads
- Controls the startup timing of multiple threads
Summarize
Lock type | Scope of application | Main functions |
---|---|---|
() |
Synchronization between threads | Mutex access to shared resources |
() |
Interprocess synchronization | Mutex access process sharing resources |
() |
Recursive call | Allows the same thread to acquire locks multiple times |
(n) |
Thread pool/connection pool | Limit the number of concurrent threads |
() |
Inter-thread communication | Waiting/notification mechanism (producer-consumer) |
() |
Inter-thread signal | Event trigger mechanism |
Use correctly in multi-threaded/multi-process programmingLockThe mechanism can prevent data competition, maintain data consistency, and improve program reliability and maintainability.
This is the end of this article about the detailed explanation of the type of lock lock in Python. For more detailed explanation of the type of lock lock in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!