Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Thread Synchronization Basics | Working with Threads
Quizzes & Challenges
Quizzes
Challenges
/
Python Multithreading and Multiprocessing

bookThread Synchronization Basics

In multithreaded programs, multiple threads often need to access and modify shared data. If two or more threads try to change a shared variable at the same time, you can encounter a race condition. A race condition happens when the outcome of a program depends on the unpredictable timing of threads, which can lead to incorrect or inconsistent results. For example, if two threads both increment a shared counter without coordination, both might read the same value before either writes back, causing one increment to be lost. To prevent this, you need a way to synchronize threads so that only one thread can access the critical section of code at a time.

Python provides synchronization primitives like the Lock from the threading module. A lock ensures that only one thread can enter a critical section at any given moment. When a thread acquires a lock, other threads trying to acquire it will wait until it is released. This prevents simultaneous access to shared resources and eliminates race conditions.

123456789101112131415161718192021
import threading counter = 0 lock = threading.Lock() def increment(): global counter for _ in range(100000): with lock: counter += 1 threads = [] for _ in range(2): t = threading.Thread(target=increment) threads.append(t) t.start() for t in threads: t.join() print("Final counter value:", counter)
copy
question-icon

Fill in the blanks to ensure that the increment function safely updates the counter variable using a lock.

import threading counter = 0 lock = threading.Lock() def increment(): global counter for _ in range(100000): # Acquire the lock before modifying counter lock.() counter += 1 # Release the lock after modification lock.() threads = [] for _ in range(2): t = threading.Thread(target=increment) threads.append(t) t.start() for t in threads: t.join() print("Final counter value:", counter)
Final counter value: 200000

Натисніть або перетягніть елементи та заповніть пропуски

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 2

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

bookThread Synchronization Basics

Свайпніть щоб показати меню

In multithreaded programs, multiple threads often need to access and modify shared data. If two or more threads try to change a shared variable at the same time, you can encounter a race condition. A race condition happens when the outcome of a program depends on the unpredictable timing of threads, which can lead to incorrect or inconsistent results. For example, if two threads both increment a shared counter without coordination, both might read the same value before either writes back, causing one increment to be lost. To prevent this, you need a way to synchronize threads so that only one thread can access the critical section of code at a time.

Python provides synchronization primitives like the Lock from the threading module. A lock ensures that only one thread can enter a critical section at any given moment. When a thread acquires a lock, other threads trying to acquire it will wait until it is released. This prevents simultaneous access to shared resources and eliminates race conditions.

123456789101112131415161718192021
import threading counter = 0 lock = threading.Lock() def increment(): global counter for _ in range(100000): with lock: counter += 1 threads = [] for _ in range(2): t = threading.Thread(target=increment) threads.append(t) t.start() for t in threads: t.join() print("Final counter value:", counter)
copy
question-icon

Fill in the blanks to ensure that the increment function safely updates the counter variable using a lock.

import threading counter = 0 lock = threading.Lock() def increment(): global counter for _ in range(100000): # Acquire the lock before modifying counter lock.() counter += 1 # Release the lock after modification lock.() threads = [] for _ in range(2): t = threading.Thread(target=increment) threads.append(t) t.start() for t in threads: t.join() print("Final counter value:", counter)
Final counter value: 200000

Натисніть або перетягніть елементи та заповніть пропуски

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 2
some-alt