Recently, we need to use Python 3 multithreading to process large data. I have explored the thread model of Python 3 by the way. Here is a brief record.
Advantages of multithreading:
- Threads can be used to process tasks that take a long time in the program in the background.
- The user interface can be more attractive and does not block the operation of the interface;
- The program can run faster.
- Make full use of the multi-core characteristics of CPU for processing;
Kernel thread: created and revoked by the operating system kernel;
User thread: it does not need the kernel to support the thread implemented in the user program;
Multithreading in Python 3:
- _thread provides some original APIs for writing multithreaded programs.
- threading provides a more convenient interface
- Both are Python 3's built-in threading modules
_thread test
#!/usr/bin/env python import _thread def print_time( threadName, delay): print (threadName) count = 0 while 1: pass count += 1 try: _thread.start_new_thread( print_time, ("Thread-1", 1, ) ) _thread.start_new_thread( print_time, ("Thread-2", 2, ) ) _thread.start_new_thread( print_time, ("Thread-3", 2, ) ) _thread.start_new_thread( print_time, ("Thread-4", 2, ) ) _thread.start_new_thread( print_time, ("Thread-5", 2, ) ) _thread.start_new_thread( print_time, ("Thread-6", 2, ) ) _thread.start_new_thread( print_time, ("Thread-7", 2, ) ) _thread.start_new_thread( print_time, ("Thread-8", 2, ) ) _thread.start_new_thread( print_time, ("Thread-9", 2, ) ) _thread.start_new_thread( print_time, ("Thread-10", 2, ) ) _thread.start_new_thread( print_time, ("Thread-11", 2, ) ) _thread.start_new_thread( print_time, ("Thread-12", 2, ) ) _thread.start_new_thread( print_time, ("Thread-13", 2, ) ) _thread.start_new_thread( print_time, ("Thread-14", 2, ) ) _thread.start_new_thread( print_time, ("Thread-15", 2, ) ) except: print ("Error: can't start thread!") while 1: pass