Implementation of thread and threading in Python
- 2020-04-02 13:58:52
- OfStack
As anyone who has ever learned Python knows, Python supports multiple threads and is a native thread. This article focuses on implementing multithreading through the two modules of thread and threading.
The thread module of python is compared with the low-level module, while the threading module of python makes some packaging for thread, which can be used more conveniently.
It's important to note that python's support for threads isn't good enough to take advantage of multiple cpus, but we'll see if this is considered in the next version of python.
So the threading module is basically objectifying a bunch of threads, creating a class called Thread.
Generally speaking, there are two modes of using threads. One is to create a function to be executed by the Thread, pass the function into the Thread object, and let it execute. The other is to inherit directly from the Thread, create a new class, and put the code that the Thread executes into the new class.
So let's look at these two approaches.
1. Python thread implements multi-threading
#-*- encoding: gb2312 -*-
import string, threading, time
def thread_main(a):
global count, mutex
# Get the thread name
threadname = threading.currentThread().getName()
for x in xrange(0, int(a)):
# In the lock
mutex.acquire()
count = count + 1
# Release the lock
mutex.release()
print threadname, x, count
time.sleep(1)
def main(num):
global count, mutex
threads = []
count = 1
# Create a lock
mutex = threading.Lock()
# Create the thread object first
for x in xrange(0, num):
threads.append(threading.Thread(target=thread_main, args=(10,)))
# Start all threads
for t in threads:
t.start()
# Waits for all child threads in the main thread to exit
for t in threads:
t.join()
if __name__ == '__main__':
num = 4
# create 4 A thread
main(4)
Second, Python threading implements multi-threading
#-*- encoding: gb2312 -*-
import threading
import time
class Test(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self._run_num = num
def run(self):
global count, mutex
threadname = threading.currentThread().getName()
for x in xrange(0, int(self._run_num)):
mutex.acquire()
count = count + 1
mutex.release()
print threadname, x, count
time.sleep(1)
if __name__ == '__main__':
global count, mutex
threads = []
num = 4
count = 1
# Create a lock
mutex = threading.Lock()
# Create a thread object
for x in xrange(0, num):
threads.append(Test(10))
# Starting a thread
for t in threads:
t.start()
# Wait for the child thread to finish
for t in threads:
t.join()
It is believed that the Python multithreading example described in this paper can provide some reference value for your Python programming.