[Python] Exclusive control using the threading module: Overview and sample code

This article introduces exclusive control using the Python threading module .

 

Example implementation

The following example uses Python's threading module to run two threads in parallel and increment a common global variable, counter .

import threading
import time
import random

# Global variable
counter = 0

# Create a lock object
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:
            # Critical section
            temp = counter
            # Add sleep to induce race condition
            time.sleep(random.random() / 1000000)
            counter = temp + 1

# Create threads
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=increment)

# Start threads
thread1.start()
thread2.start()

# Wait for threads to finish
thread1.join()
thread2.join()

print(f'Final counter value: {counter}')

 

Importing libraries

import threading
import time
import random

 

  • Import the threading module to create and manage threads .
  • Import the time module for time management and the random module to generate random sleep times .

Creating a Lock Object

lock = threading.Lock()

 

Creates a lock object to perform exclusive control between threads.

Defining the increment function

def increment():
    global counter
    for _ in range(100000):
        # with lock:  # Comment out lock
            # Critical section
            temp = counter
            # Add sleep to induce race condition
            time.sleep(random.random() / 10000)
            counter = temp + 1

 

Define a function that increments the counter .

The value of counter is saved in a temporary variable temp , and then a short random sleep is performed to intentionally induce thread contention.

Creating and starting threads

thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=increment)

thread1.start()
thread2.start()

 

Create two threads and start each one with the increment function as its target.

Wait for a thread to finish

thread1.join()
thread2.join()

 

The main thread waits for the two threads to finish.

 

Execution result

When you run this program, the following message will be output to standard output. Because the counter is locked by a spinlock, the final counter value will be 200000.

Final counter value: 200000

 

If you run it without mutual exclusion, the result will be as follows. You can see that because mutual exclusion is not used, a conflict occurs and the counter cannot be incremented correctly.

Final counter value: 100002

Comments