Fundamentals 13 min read

Master Python Threading: From Basics to Advanced Synchronization

This article explains Python threading fundamentals, including thread context, kernel vs. user threads, the low‑level _thread module and the high‑level threading module, functional and class‑based thread creation, synchronization with locks, and using Queue for thread‑safe communication, all illustrated with complete code examples.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Threading: From Basics to Advanced Synchronization

Each independent thread has an entry point, a sequential execution flow, and an exit point, but a thread cannot run on its own; it must exist within an application that controls multiple threads.

Every thread maintains its own set of CPU registers, called the thread context, which records the state of the registers from the thread's last execution.

The instruction pointer and stack pointer registers are the two most important registers in a thread’s context; they reference memory addresses within the process’s address space.

Threads can be preempted (interrupted).

Threads can be temporarily suspended (sleep), which is called yielding.

Threads can be classified as:

Kernel threads: created and destroyed by the operating system kernel.

User threads: implemented in user programs without kernel support.

Python 3 provides two common modules for threading:

_thread
threading

(recommended)

Functional style

Use _thread.start_new_thread() to create a new thread. Syntax:

_thread.start_new_thread(function, args[, kwargs])

Parameters: function – the thread function. args – a tuple of arguments passed to the function. kwargs – optional keyword arguments.

import _thread, time

def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("{}: {}".format(threadName, time.ctime(time.time())))

try:
    _thread.start_new_thread(print_time, ("Thread-1", 2))
    _thread.start_new_thread(print_time, ("Thread-2", 4))
except:
    print("Error")

while 1:
    pass  # keep main thread alive

Sample output shows timestamps from both threads.

Class‑based style

The threading module adds higher‑level methods: threading.currentThread() – returns the current thread object. threading.enumerate() – returns a list of all alive threads. threading.activeCount() – returns the number of alive threads.

The Thread class provides methods such as run(), start(), join(), isAlive(), getName(), and setName().

import threading, time

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("Thread Start: " + self.name)
        print_time(self.name, self.counter, 5)
        print("Thread Exit: " + self.name)

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print("{}: {}".format(threadName, time.ctime()))
        counter -= 1

thread1 = myThread(1001, "Thread-1", 1)
thread2 = myThread(1002, "Thread-2", 2)
print("Thread-1 is Alive?", thread1.isAlive())
thread1.start()
thread2.start()
print("Thread-1 is Alive?", thread1.isAlive())
thread1.join()
thread2.join()
print("Thread-1 is Alive?", thread1.isAlive())
print("exit")

It demonstrates that a thread becomes active only after start() is called, and join() blocks until the thread finishes.

Thread synchronization

When multiple threads share data, synchronization is needed. Using Lock (or RLock) with acquire() and release() ensures that only one thread accesses the critical section at a time.

import threading, time

threadLock = threading.Lock()
threads = []

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("Thread Start: " + self.name)
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        threadLock.release()
        print("Thread Exit: " + self.name)

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print("{}: {}".format(threadName, time.ctime()))
        counter -= 1

thread1 = myThread(1001, "Thread-1", 1)
thread2 = myThread(1002, "Thread-2", 2)
thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)
for t in threads:
    t.join()
print("exit")

Thread‑safe priority queue

The queue module offers thread‑safe queues such as Queue, LifoQueue, and PriorityQueue, which can be used for inter‑thread communication and synchronization.

Common Queue methods: qsize() – returns the number of items. empty() – True if the queue is empty. full() – True if the queue is full. get([block, timeout]) – removes and returns an item. put(item, [block, timeout]) – adds an item. task_done() – signals that a formerly enqueued task is complete. join() – blocks until all items have been processed.

import queue, threading, time

exitFlag = 0
queueLock = threading.Lock()
workQueue = queue.Queue(10)

class myThread(threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q

    def run(self):
        print("Thread Start: " + self.name)
        process_data(self.name, self.q)
        print("Thread Exit: " + self.name)

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print("{} processing {}".format(threadName, data))
        else:
            queueLock.release()
        time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
threads = []
threadID = 1
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

queueLock.acquire()
print("Filling queue...")
time.sleep(1)
for word in ["One", "Two", "Three", "Four", "Five"]:
    workQueue.put(word)
print("Queue filled.")
queueLock.release()

while not workQueue.empty():
    pass

exitFlag = 1
for t in threads:
    t.join()
print("exit")

The examples show that start() launches a thread, join() waits for its completion, and proper use of locks and queues enables safe concurrent execution.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonconcurrencySynchronizationmultithreadingthreadingQueue
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.