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

Python Multithreading

Python Multithreading

Multithreading is like executing several different programs at the same time; running multiple threads has the following advantages:

Threads differ from processes during execution. Each independent process has an entry point for program execution, a sequential execution sequence, and an exit point. However, a thread cannot execute independently; it must exist within an application, which provides control over the execution of multiple threads.

Each thread has its own set of CPU registers, called the thread context, which reflects the state of the CPU registers from the last time that thread ran.

The instruction pointer and stack pointer registers are the two most important registers in a thread context; a thread always runs within the context of a process, and these addresses are used to mark memory in the address space of the process that owns the thread.

Getting started with Python threads

There are two ways to use threads in Python: with a function, or by wrapping a thread object in a class.

Functional style: call the start_new_thread() function in the thread module to create a new thread. The syntax is as follows:


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

Parameter description:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

import

thread

import

time

Define a function for the thread

def

print_time

(

threadName

,

delay

)

:

count

=

0

while

count

<

5

:

time

.

sleep

(

delay

)

count

+=

1

print

"

%s: %s

"

%

(

threadName

,

time

.

ctime

(

time

.

time

(

)

)

)

Create two threads

try

:

thread

.

start_new_thread

(

print_time

,

(

"

Thread-1

"

,

2

,

)

)

thread

.

start_new_thread

(

print_time

,

(

"

Thread-2

"

,

4

,

)

)

except

:

print

"

Error: unable to start thread

"

while

1

:

pass

Running the above program produces the following output:


Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009

A thread usually ends when its thread function ends naturally; you can also call thread.exit() within a thread function, which raises a SystemExit exception to exit the thread.


Thread modules

Python provides support for threads through two standard libraries, thread and threading. thread provides low-level, primitive threads and a simple lock.

Other methods provided by the threading module:

In addition to using methods, the thread module also provides the Thread class for handling threads. The Thread class provides the following methods:


Creating Threads with the Threading Module

To create a thread with the Threading module, inherit directly from threading.Thread and then override the __init__ method and the run method:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

import

threading

import

time

exitFlag

=

0

class

myThread

(

threading

.

Thread

)

:

# Inherit from the parent class threading.Thread

def

init

(

self

,

threadID

,

name

,

counter

)

:

threading

.

Thread

.

init

(

self

)

self

.

threadID

=

threadID

self

.

name

=

name

self

.

counter

=

counter

def

run

(

self

)

:

# Write the code to be executed inside the run function. After the thread is created, it will run the run function directly.

print

"

Starting

"

self

.

name

print_time

(

self

.

name

,

self

.

counter

,

5

)

print

"

Exiting

"

self

.

name

def

print_time

(

threadName

,

delay

,

counter

)

:

while

counter

:

if

exitFlag

:

(

threading

.

Thread

)

.

exit

(

)

time

.

sleep

(

delay

)

print

"

%s: %s

"

%

(

threadName

,

time

.

ctime

(

time

.

time

(

)

)

)

counter

-=

1

Create new threads

thread1

=

myThread

(

1

,

"

Thread-1

"

,

1

)

thread2

=

myThread

(

2

,

"

Thread-2

"

,

2

)

Start the thread

thread1

.

start

(

)

thread2

.

start

(

)

print

"

Exiting Main Thread

"

The result of running the above program is as follows;


Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2

Thread synchronization

If multiple threads modify the same data together, unpredictable results may occur; to ensure data correctness, the threads need to be synchronized.

Simple thread synchronization can be achieved using the Lock and Rlock objects of Thread objects. Both objects have an acquire method and a release method. For data that only one thread should operate on at a time, you can place the operation between the acquire and release methods. As follows:

The advantage of multithreading is that several tasks can run at the same time (or at least it feels that way). But when threads need to share data, there can be data synchronization problems.

Consider a situation where all elements in a list are 0, the thread 'set' changes all elements to 1 from back to front, while the thread 'print' is responsible for reading and printing the list from front to back.

Then it may happen that just as the thread "set" starts changing, the thread "print" comes to print the list, so the output is half 0s and half 1s; this is data out of sync. To avoid this, the concept of a lock is introduced.

A lock has two states - locked and unlocked. Whenever a thread such as "set" wants to access shared data, it must first acquire the lock; if another thread such as "print" has already acquired the lock, then the thread "set" is paused, that is, synchronously blocked; once the thread "print" finishes accessing and releases the lock, the thread "set" can continue.

With this handling, printing the list outputs either all 0s or all 1s, and the awkward situation of half 0s and half 1s no longer occurs.

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

import

threading

import

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

"

Starting

"

self

.

name

Acquire the lock; returns True after the lock is successfully acquired.

If the optional timeout parameter is not filled in, it will block until the lock is acquired.

Otherwise, it returns False after a timeout.

threadLock

.

acquire

(

)

print_time

(

self

.

name

,

self

.

counter

,

3

)

Release the lock

threadLock

.

release

(

)

def

print_time

(

threadName

,

delay

,

counter

)

:

while

counter

:

time

.

sleep

(

delay

)

print

"

%s: %s

"

%

(

threadName

,

time

.

ctime

(

time

.

time

(

)

)

)

counter

-=

1

threadLock

=

threading

.

Lock

(

)

threads

=

[

]

Create new threads

thread1

=

myThread

(

1

,

"

Thread-1

"

,

1

)

thread2

=

myThread

(

2

,

"

Thread-2

"

,

2

)

Start the new threads

thread1

.

start

(

)

thread2

.

start

(

)

Add the thread to the thread list

threads

.

append

(

thread1

)

threads

.

append

(

thread2

)

Wait for all threads to complete

for

t

in

threads

:

t

.

join

(

)

print

"

Exiting Main Thread

"


Thread priority queue (Queue)

Python's Queue module provides synchronized, thread-safe queue classes, including the FIFO (first in, first out) queue Queue, the LIFO (last in, first out) queue LifoQueue, and the priority queue PriorityQueue. These queues all implement lock primitives and can be used directly in multithreading. Queues can be used to achieve synchronization between threads.

Commonly used methods in the Queue module:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

import

Queue

import

threading

import

time

exitFlag

=

0

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

"

Starting

"

self

.

name

process_data

(

self

.

name

,

self

.

q

)

print

"

Exiting

"

self

.

name

def

process_data

(

threadName

,

q

)

:

while

not

exitFlag

:

queueLock

.

acquire

(

)

if

not

workQueue

.

empty

(

)

:

data

=

q

.

get

(

)

queueLock

.

release

(

)

print

"

%s processing %s

"

%

(

threadName

,

data

)

else

:

queueLock

.

release

(

)

time

.

sleep

(

1

)

threadList

=

[

"

Thread-1

"

,

"

Thread-2

"

,

"

Thread-3

"

]

nameList

=

[

"

One

"

,

"

Two

"

,

"

Three

"

,

"

Four

"

,

"

Five

"

]

queueLock

=

threading

.

Lock

(

)

workQueue

=

Queue

.

Queue

(

10

)

threads

=

[

]

threadID

=

1

Create new threads

for

tName

in

threadList

:

thread

=

myThread

(

threadID

,

tName

,

workQueue

)

thread

.

start

(

)

threads

.

append

(

thread

)

threadID

+=

1

Fill the queue

queueLock

.

acquire

(

)

for

word

in

nameList

:

workQueue

.

put

(

word

)

queueLock

.

release

(

)

Wait for the queue to empty

while

not

workQueue

.

empty

(

)

:

pass

Notify the threads that it is time to exit

exitFlag

=

1

Wait for all threads to complete

for

t

in

threads

:

t

.

join

(

)

print

"

Exiting Main Thread

"

The result of running the above program:


Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread