Python Multitasking Programming - The Use of Multithreading

1. Import the thread package



import threading

In CPython , due to the global interpreter lock, only one thread can execute Python code at a time (although some performance-oriented libraries may remove this limitation). If you want your application to make better use of the computing resources of multi-core computers, it is recommended that you use multiprocessing or concurrent.futures.ProcessPoolExecutor . However, if you want to run multiple I/O intensive tasks simultaneously, multithreading is still an appropriate model.


2. Create a thread



threading.Thread (group=None, target=None, name=None, args =(), kwargs ={}, *, daemon=None)
reserved for future ThreadGroup classes
name is the thread name, generally do not need to be set
target: the object to be executed, executed by the run() method
args : target tuple to pass arguments
kwargs : target dictionary parameters
daemon: whether it is a daemon process

demo1_process = threading.Thread ( target _ _ = dance )
demo2_process = threading.Thread ( target _ _ = sing )

3. Start the thread



Common method: use the start method
dance_process.start ( ) _ _
sing_process.start ( ) _ _

4. Code implementation



#import thread module
import threading
import time

def dance ( ):
for i in range ( 3 ):
print ( "dance..." )
time.sleep ( 0.5 ) _ _

def sing ( ):
for i in range ( 3 ):
print ( "sing..." )
time.sleep ( 0.5 ) _ _



if __name__ == "__main__" :
#create thread
dance_process = threading . Thread ( target = dance )
sing_process = threading.Thread ( target = sing ) _ _
#start thread
dance_process.start ( ) _ _
sing_process.start ( ) _ _
operation result:



Copyright statement: The content of this article is contributed by Alibaba Cloud's real-name registered users. The copyright belongs to the original author. The Alibaba Cloud developer community does not own the copyright and does not assume the corresponding legal responsibility. For specific rules, please refer to the " Alibaba Cloud Developer Community User Service Agreement " and " Alibaba Cloud Developer Community Intellectual Property Protection Guidelines ". If you find any content suspected of plagiarism in this community, fill out the infringement complaint form to report it. Once verified, this community will delete the allegedly infringing content immediately.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00