This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022.
Python multithreading
Python implements multithreading primarily through the thread and threading modules. The Thread module of Python is a low-level module. The Threading module of Python encapsulates threads and makes them easier to use.
There are two ways to create a new thread:
- through
threading.Thread()
Passed to theThread
Object An executable method (or object) - inheritance
threading.Thread
Define subclasses and overriderun()
methods
threading.Thread()
Main parameters:
target
: Callable, executable methodname
: STR, thread nameargs
: Iterable[Any], the argument list of the executable methoddaemon
Bool Indicates whether this thread is a daemon thread
The sample code
import random
import threading
from time import sleep
def myPrint(odd: bool) :
"""odd is True and prints odd, otherwise prints even """
for i in range(10) :if odd and i % 2= =1:
print(i)
elif not odd and i % 2= =0:
print(i)
sleep(random.random())
t1 = threading.Thread(target= myPrint, args=(True, ))
t2 = threading.Thread(target= myPrint, args=(False, ))
t1.start()
t2.start()
Copy the code
Run the code to mix odd and even numbers, instead of printing all odd numbers first and then all even numbers.
inheritancethreading.Thread
Create multiple threads by subclassing threading.Thread directly from threading.Thread and overriding the init and run methods. Because of the inheritance from threading.Thread, when the start method is called, the code in its run method is automatically run.
Sample code:
class myCPrint(threading.Thread) :
def __init__(self , odd) :
super(myCPrint,self).__init__()
self.odd = odd
def run(self) :
for i in range(10) :if self.odd and i % 2= =1:
print(i)
elif not self.odd and i % 2= =0:
print(i)
sleep(random.random())
c1 = myCPrint(True)
c2 = myCPrint(False)
c1.start()
c2.start()
Copy the code
When you run the code, you can also see a mixture of odd and even numbers, instead of printing all odd numbers first and then all even numbers.
Problems with multithreading in Python
Multithreading in Python is false multithreading
Execution of Python code is controlled by the Python virtual machine (interpreter). Python was designed with only one thread executing at a time in the main loop. Access to the Python virtual machine is controlled by the global interpreter lock (GIL), which ensures that only one thread is running at a time. In a multithreaded environment, the Python virtual machine executes as follows:
- Set the GIL
- Switch to a thread and execute
- Thread execution completed or set to sleep (up to 100 bytes)
- Unlock the GIL
- Repeat 1-4
No matter how many cores there are, cores can only run one thread per unit of time, and then the time slice rotates.
If you want to take full advantage of multiple cores, you can use the multiprocessing library to create multiple processes.