Synchronization and Communication
Deslize para mostrar o menu
When working with threads or processes, you often need to share data or coordinate their actions. Without proper synchronization, two threads might try to update the same variable at the same time, leading to unpredictable results known as race conditions. To prevent this, Python provides synchronization primitives such as locks, queues, and shared memory.
A lock is a simple mechanism that ensures only one thread can access a piece of code or data at a time. If one thread acquires a lock, other threads trying to acquire it will have to wait until it is released. This prevents multiple threads from making conflicting changes.
Queues are another powerful tool for safe communication between threads and processes. A queue allows one thread or process to safely put data in, while another takes it out. The queue.Queue class (for threads) and multiprocessing.Queue (for processes) handle all the necessary locking internally, so you do not have to worry about race conditions.
With shared memory, processes can access the same data directly, but you must use synchronization primitives like locks or semaphores to avoid conflicts. In most cases, using queues is simpler and safer for inter-process communication.
The video above shows how a lock can prevent two threads from corrupting shared data, and how a queue can be used to safely pass data between concurrent tasks.
1234567891011121314151617181920212223import threading counter = 0 lock = threading.Lock() def increment(): global counter for _ in range(10000): with lock: # Ensuring only one thread enters this block at a time counter += 1 threads = [] for _ in range(5): t = threading.Thread(target=increment) threads.append(t) t.start() for t in threads: t.join() print("Final counter value:", counter) # Without the lock, the final value would likely be wrong due to race conditions. # With the lock, the result is always correct: 50000.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo