Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python threading Module

Python threading Module

Python's threading The module is one of the standard library modules used to implement multithreaded programming. Multithreading allows a program to execute several tasks at the same time, improving efficiency and responsiveness.

threading The module provides tools for creating and managing threads, making it easy for developers to write concurrent programs.

What is a thread?

You can think of threads as employees in an office:

In computer science:

Why use multithreading?

In a single-threaded program, tasks are executed one after another in sequence. If a task needs to wait (for example, waiting for a network response or a file read), the whole program is blocked until that task finishes. Multithreading lets the program continue executing other tasks while one task is waiting, improving overall performance.

Python threads and the Global Interpreter Lock (GIL)

Python has a mechanism called the Global Interpreter Lock (GIL), which ensures that at any moment only one thread can execute Python bytecode.

What does this mean? For CPU-intensive tasks (such as scientific computing or image processing), because of the GIL, multithreading usually cannot take advantage of multiple cores to speed up computation, and may even be slower because of the overhead of thread switching.

So where are Python threads useful? For I/O-intensive tasks (such as network requests, reading and writing files, or waiting for user input), a thread releases the GIL while waiting for the I/O operation to complete, allowing other threads to run. This can significantly improve a program's overall responsiveness and efficiency, because while you are waiting for one web page response the program can handle another task.


How to use the threading module?

Use threading The first step with the module is to import it:


import threading
import time  # 用于模拟耗时操作

The most basic way to create a thread is to use threading.Thread class.

Syntax explanation:


thread_obj = threading.Thread(target=函数名, args=(参数元组,))

1. Create a thread

In Python, you can create a thread by subclassing the threading.Thread class or by using the threading.Thread constructor directly.

Method 1: subclass threading.Thread class

Example

import

threading

class

MyThread

(

threading

.

Thread

)

:

   

def

run

(

self

)

:

       

print

(

"Thread starts executing"

)

       

Write the code the thread should execute here

       

print

(

"Thread execution finished"

)

Create a thread instance

thread

=

MyThread

(

)

Start a thread

thread

.

start

(

)

Wait for the thread to finish

thread

.

join

(

)

print

(

"Main thread ends"

)

Method 2: use threading.Thread constructor

Example

import

threading

def

my_function

(

)

:

   

print

(

"Thread starts executing"

)

   

Write the code the thread should execute here

   

print

(

"Thread execution finished"

)

Create a thread instance

thread

=

threading

.

Thread

(

target

=

my_function

)

Start a thread

thread

.

start

(

)

Wait for the thread to finish

thread

.

join

(

)

print

(

"Main thread ends"

)

2. Thread synchronization

In multithreaded programming, several threads may access a shared resource at the same time, which can lead to data inconsistency. To avoid this, you can use thread synchronization mechanisms such as locks (Lock)。

Example

import

threading

Create a lock object

lock

=

threading

.

Lock

(

)

def

my_function

(

)

:

   

with

lock:

       

print

(

"Thread starts executing"

)

       

Write the code the thread should execute here

       

print

(

"Thread execution finished"

)

Create a thread instance

thread1

=

threading

.

Thread

(

target

=

my_function

)

thread2

=

threading

.

Thread

(

target

=

my_function

)

Start a thread

thread1.

start

(

)

thread2.

start

(

)

Wait for the thread to finish

thread1.

join

(

)

thread2.

join

(

)

print

(

"Main thread ends"

)

3. Communication between threads

Communication between threads can be achieved with a queue (Queue).Queue is thread-safe and can pass data safely between multiple threads.

Example

import

threading

import

queue

def

worker

(

q

)

:

   

while

not

q.

empty

(

)

:

        item

=

q.

get

(

)

       

print

(

f

"Processing item: {item}"

)

        q.

task_done

(

)

Create a queue and fill it with data

q

=

queue.

Queue

(

)

for

i

in

range

(

10

)

:

    q.

put

(

i

)

Create a thread instance

thread1

=

threading

.

Thread

(

target

=

worker

,

args

=

(

q

,

)

)

thread2

=

threading

.

Thread

(

target

=

worker

,

args

=

(

q

,

)

)

Start a thread

thread1.

start

(

)

thread2.

start

(

)

Wait until all items in the queue have been processed

q.

join

(

)

print

(

"All items processed"

)


Common classes, methods and attributes

1. Core classes

Class / method / attribute Description Example
threading.Thread Thread class, used to create and manage threads t = Thread(target=func, args=(1,))
threading.Lock Mutex (primitive lock) lock = Lock()
threading.RLock Reentrant lock (can be acquired multiple times by the same thread) rlock = RLock()
threading.Event Event object, used for thread synchronization event = Event()
threading.Condition Condition variable, for complex thread coordination cond = Condition()
threading.Semaphore Semaphore, controls the number of concurrent threads sem = Semaphore(3)
threading.BoundedSemaphore Bounded semaphore (prevents the count from exceeding its initial value) b_sem = BoundedSemaphore(2)
threading.Timer Timer thread, delayed execution timer = Timer(5.0, func)
threading.local Thread-local data (stored independently for each thread) local_data = threading.local()

2. Common methods / attributes of the Thread object

Method/attribute Description Example
start() Start a thread t.start()
run() The method a thread executes (can be overridden) Override this method in a custom class
join(timeout=None) Block the current thread until the target thread ends t.join()
is_alive() Check whether the thread is running if t.is_alive():
name Thread name (can be changed) t.name = "Worker-1"
daemon Daemon thread flag (ends automatically when the main thread exits) t.daemon = True
ident Thread identifier ( None) print(t.ident)

3. Common methods of Lock / RLock

Method Description Example
acquire(blocking=True, timeout=-1) Acquire the lock (blocking or non-blocking) lock.acquire()
release() Release the lock lock.release()
locked() Check whether the lock is held if not lock.locked():

4. Common methods of Event

Method Description Example
set() Set the event to true and wake all waiting threads event.set()
clear() Reset the event to false event.clear()
wait(timeout=None) Block until the event is true or a timeout occurs event.wait(2.0)
is_set() Check the event state if event.is_set():

5. Common methods of Condition

Method Description Example
wait(timeout=None) Release the lock and block until notified or a timeout occurs cond.wait()
notify(n=1) Wake up at most n waiting threads cond.notify(2)
notify_all() Wake all waiting threads cond.notify_all()

6. Module-level functions / attributes

Function / attribute Description Example
threading.active_count() Return the number of currently active threads print(threading.active_count())
threading.current_thread() Return the current thread object print(threading.current_thread().name)
threading.enumerate() Return a list of all active threads for t in threading.enumerate():
threading.main_thread() Return the main thread object if threading.current_thread() is threading.main_thread():
threading.get_ident() Return the identifier of the current thread (Python 3.3+) print(threading.get_ident())

Example

  1. Basic thread creation

Example

import

threading

def

worker

(

num

)

:

   

print

(

f

"Worker {num} started"

)

threads

=

[

]

for

i

in

range

(

3

)

:

    t

=

threading

.

Thread

(

target

=

worker

,

args

=

(

i

,

)

)

    threads.

append

(

t

)

    t.

start

(

)

for

t

in

threads:

    t.

join

(

)

  1. Use a lock to protect shared resources

Example

lock

=

threading

.

Lock

(

)

count

=

0

def

increment

(

)

:

   

global

count

   

with

lock:  

Acquire and release the lock automatically

        count +

=

1

threads

=

[

threading

.

Thread

(

target

=

increment

)

for

_

in

range

(

10

)

]

for

t

in

threads:

    t.

start

(

)

for

t

in

threads:

    t.

join

(

)

print

(

count

)

 

Output: 10

  1. Event synchronization

Example

event

=

threading

.

Event

(

)

def

waiter

(

)

:

   

print

(

"Waiting for event..."

)

    event.

wait

(

)

   

print

(

"Event triggered!"

)

t

=

threading

.

Thread

(

target

=

waiter

)

t.

start

(

)

The main thread triggers the event

threading

.

Event

(

)

.

wait

(

2.0

)

 

Simulate a delay

event.

set

(

)

t.

join

(

)

  1. Producer-consumer model (Condition)

Example

import

random

from

threading

import

Condition

queue

=

[

]

cond

=

Condition

(

)

MAX_ITEMS

=

5

def

producer

(

)

:

   

for

_

in

range

(

10

)

:

       

with

cond:

           

while

len

(

queue

)

=

MAX_ITEMS:

                cond.

wait

(

)

            item

=

random

.

randint

(

1

,

100

)

            queue.

append

(

item

)

           

print

(

f

"Produced {item}"

)

            cond.

notify

(

)

def

consumer

(

)

:

   

for

_

in

range

(

10

)

:

       

with

cond:

           

while

not

queue:

                cond.

wait

(

)

            item

=

queue.

pop

(

0

)

           

print

(

f

"Consumed {item}"

)

            cond.

notify

(

)

threading

.

Thread

(

target

=

producer

)

.

start

(

)

threading

.

Thread

(

target

=

consumer

)

.

start

(

)


Notes

  1. Global Interpreter Lock (GIL): Python's GIL restricts execution so that only one thread runs Python bytecode at a time. Therefore, for CPU-intensive tasks, multithreading may not improve performance. For I/O-intensive tasks, multithreading is still beneficial.

  2. Thread Safety: In a multithreaded environment, make sure access to shared resources is thread-safe and avoid data races and deadlocks.

  3. Number of threads: Creating too many threads can exhaust system resources and hurt performance. Keep the thread count reasonable, or use a thread pool (ThreadPoolExecutor) to manage threads.


Quiz

** threading module knowledge quiz