Concurrency with Threading

Advanced PythonConcurrencyFree Lesson

Advertisement

Introduction

Threading allows concurrent execution of multiple tasks within the same process.

Basic Threading

import threading

def task(name, delay):
    print(f"{name} starting")
    time.sleep(delay)
    print(f"{name} finished")

# Create threads
t1 = threading.Thread(target=task, args=("A", 1))
t2 = threading.Thread(target=task, args=("B", 2))

# Start and join
t1.start()
t2.start()
t1.join()
t2.join()

Thread Synchronization

# Lock
lock = threading.Lock()
with lock:
    shared_counter += 1

# RLock (reentrant lock)
rlock = threading.RLock()

# Semaphore
semaphore = threading.Semaphore(3)

# Event
event = threading.Event()
event.wait(timeout=5)
event.set()

Thread-Safe Data Structures

from queue import Queue

# Thread-safe queue
q = Queue()
q.put(item)
item = q.get()

# With maxsize
bounded_q = Queue(maxsize=10)

Practice Problems

  1. Create producer-consumer pattern with threads
  2. Use locks to protect shared resources
  3. Implement thread pool manually
  4. Handle Ctrl+C gracefully in threads
  5. Measure performance with threading

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement