Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Synchronization and Communication | Multithreading vs. Multiprocessing
Python Structural Programming

Synchronization and Communication

Swipe um das Menü anzuzeigen

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.

1234567891011121314151617181920212223
import 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.
question mark

Which synchronization primitive would you use to safely share data between multiple threads in Python?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 6

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 3. Kapitel 6
some-alt