Python3 Multithreading
Multithreading is like executing several different programs at the same time; running multiple threads has the following advantages:
- Threads let you move long-running tasks in a program to the background.
- User interfaces can be more attractive; for example, when a user clicks a button to trigger processing of some event, a progress bar can pop up to show the progress.
- The program may run faster.
- Threads are useful for waiting tasks such as user input, file reading and writing, and sending and receiving data over a network. In such cases we can free up precious resources such as memory usage.
Each independent thread has an entry point for program execution, a sequential execution sequence and a program exit. But 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.
- A thread can be preempted (interrupted).
- While other threads are running, a thread can be temporarily set aside (also called sleeping) -- this is thread yielding.
Threads can be divided into:
- **Kernel threads:** created and destroyed by the operating system kernel.
- **User threads:** threads implemented in a user program without kernel support.
The two commonly used modules for threads in Python3 are:
- _thread
- threading (recommended)
The thread module has been deprecated. Users can use the threading module instead, so the "thread" module can no longer be used in Python3. For compatibility, Python3 renamed thread to "_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:
- function - the thread function.
- args - the arguments passed to the thread function; it must be of type tuple.
- kwargs - optional arguments.
Example
#!/usr/bin/python3
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
(
"%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
:
(
"Error: unable to start thread"
)
while
1
:
pass
Running the above program produces the following output:
Thread-1: Wed Jan 5 17:38:08 2022
Thread-2: Wed Jan 5 17:38:10 2022
Thread-1: Wed Jan 5 17:38:10 2022
Thread-1: Wed Jan 5 17:38:12 2022
Thread-2: Wed Jan 5 17:38:14 2022
Thread-1: Wed Jan 5 17:38:14 2022
Thread-1: Wed Jan 5 17:38:16 2022
Thread-2: Wed Jan 5 17:38:18 2022
Thread-2: Wed Jan 5 17:38:22 2022
Thread-2: Wed Jan 5 17:38:26 2022
After running the above program you can press ctrl-c to exit.
Thread modules
Python3 provides support for threads through two standard libraries, _thread and threading.
_thread provides low-level, primitive threads and a simple lock; its functionality is rather limited compared with the threading module.
Besides containing all the methods of the _thread module, the threading module also provides the following methods:
- threading.current_thread(): Returns the current thread variable.
- threading.enumerate(): Returns a list containing the running threads. Running means after the thread has started and before it has ended, excluding threads before start and after termination.
- threading.active_count(): Returns the number of running threads, the same result as len(threading.enumerate()).
- threading.Thread(target, args=(), kwargs={}, daemon=None):
- creation
Threadan instance of the class. target: The target function the thread will execute.args: Arguments of the target function, passed as a tuple.kwargs: Keyword arguments of the target function, passed as a dictionary.daemon: Specifies whether the thread is a daemon thread.
The threading.Thread class provides the following methods and attributes:
-
__init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None):
Threadobject.group: The thread group, currently unused and reserved for future extension.target: The target function the thread will execute.name: The name of the thread.args: Arguments of the target function, passed as a tuple.kwargs: Keyword arguments of the target function, passed as a dictionary.daemon: Specifies whether the thread is a daemon thread.-
start(self):
run()method.-
run(self):
-
join(self, timeout=None):
join()blocks until the called thread terminates. If thetimeoutparameter is specified, it waits at mosttimeoutseconds.-
is_alive(self):
True; otherwise, returnsFalse。-
getName(self):
-
setName(self, name):
-
identproperty through the following steps:
-
daemonproperty through the following steps:
-
isDaemon()method in the component:
A simple threading example:
Example
import
threading
import
time
def
print_numbers
(
)
:
for
i
in
range
(
5
)
:
time
.
sleep
(
1
)
(
i
)
Create a thread
thread
=
threading
.
Thread
(
target
=
print_numbers
)
Start a thread
thread
.
start
(
)
Wait for the threads to finish
thread
.
join
(
)
The output is:
0
1
2
3
4
Creating threads with the threading module
We can create a new subclass by inheriting directly from threading.Thread, instantiate it and call start() to launch a new thread, which calls the thread's run() method:
Example
#!/usr/bin/python3
import
threading
import
time
exitFlag
=
0
class
myThread
(
threading
.
Thread
)
:
def
init
(
self
,
threadID
,
name
,
delay
)
:
threading
.
Thread
.
init
(
self
)
self
.
threadID
=
threadID
self
.
name
=
name
self
.
delay
=
delay
def
run
(
self
)
:
(
"Starting thread: "
self
.
name
)
print_time
(
self
.
name
,
self
.
delay
,
5
)
(
"Exiting thread: "
self
.
name
)
def
print_time
(
threadName
,
delay
,
counter
)
:
while
counter:
if
exitFlag:
threadName.
exit
(
)
time
.
sleep
(
delay
)
(
"%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 new threads
thread1.
start
(
)
thread2.
start
(
)
thread1.
join
(
)
thread2.
join
(
)
(
"Exiting main thread"
)
The result of running the above program is as follows;
开始线程:Thread-1
开始线程:Thread-2
Thread-1: Wed Jan 5 17:34:54 2022
Thread-2: Wed Jan 5 17:34:55 2022
Thread-1: Wed Jan 5 17:34:55 2022
Thread-1: Wed Jan 5 17:34:56 2022
Thread-2: Wed Jan 5 17:34:57 2022
Thread-1: Wed Jan 5 17:34:57 2022
Thread-1: Wed Jan 5 17:34:58 2022
退出线程:Thread-1
Thread-2: Wed Jan 5 17:34:59 2022
Thread-2: Wed Jan 5 17:35:01 2022
Thread-2: Wed Jan 5 17:35:03 2022
退出线程: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 with the Lock and RLock objects of Thread; both have acquire and release methods. For data that must be operated on by only one thread at a time, the operation can be placed 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 this situation: all elements of a list are 0, the thread "set" changes all elements to 1 from back to front, while the thread "print" reads the list from front to back and prints it.
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
#!/usr/bin/python3
import
threading
import
time
class
myThread
(
threading
.
Thread
)
:
def
init
(
self
,
threadID
,
name
,
delay
)
:
threading
.
Thread
.
init
(
self
)
self
.
threadID
=
threadID
self
.
name
=
name
self
.
delay
=
delay
def
run
(
self
)
:
(
"Starting thread: "
self
.
name
)
Acquire the lock for thread synchronization
threadLock.
acquire
(
)
print_time
(
self
.
name
,
self
.
delay
,
3
)
Release the lock to start the next thread
threadLock.
release
(
)
def
print_time
(
threadName
,
delay
,
counter
)
:
while
counter:
time
.
sleep
(
delay
)
(
"%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
(
)
(
"Exiting main thread"
)
Running the above program, the output is:
开启线程: Thread-1
开启线程: Thread-2
Thread-1: Wed Jan 5 17:36:50 2022
Thread-1: Wed Jan 5 17:36:51 2022
Thread-1: Wed Jan 5 17:36:52 2022
Thread-2: Wed Jan 5 17:36:54 2022
Thread-2: Wed Jan 5 17:36:56 2022
Thread-2: Wed Jan 5 17:36:58 2022
退出主线程
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 multithreaded programs; queues can be used to achieve synchronization between threads.
Common methods in the Queue module:
- Queue.qsize() returns the size of the queue
- Queue.empty() returns True if the queue is empty, False otherwise
- Queue.full() returns True if the queue is full, False otherwise
- Queue.full corresponds to the maxsize value
- Queue.get([block[, timeout]]) gets from the queue; timeout is the waiting time
- Queue.get_nowait() is equivalent to Queue.get(False)
- Queue.put(item) writes to the queue; timeout is the waiting time
- Queue.put_nowait(item) is equivalent to Queue.put(item, False)
- Queue.task_done() sends a signal to the queue that a task has been completed after finishing a piece of work
- Queue.join() actually means waiting until the queue is empty before performing other operations
Example
#!/usr/bin/python3
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
)
:
(
"Starting thread:"
self
.
name
)
process_data
(
self
.
name
,
self
.
q
)
(
"Exiting thread: "
self
.
name
)
def
process_data
(
threadName
,
q
)
:
while
not
exitFlag:
queueLock.
acquire
(
)
if
not
workQueue.
empty
(
)
:
data
=
q.
get
(
)
queueLock.
release
(
)
(
"%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
(
)
(
"Exiting main thread"
)
The result of running the above program:
开启线程:Thread-1
开启线程:Thread-2
开启线程:Thread-3
Thread-3 processing One
Thread-1 processing Two
Thread-2 processing Three
Thread-3 processing Four
Thread-1 processing Five
退出线程:Thread-3
退出线程:Thread-2
退出线程:Thread-1
退出主线程