1. Multithreading:
Multithreading is to synchronize multiple tasks, not to improve operational efficiency, but to improve the efficiency of resource use to improve the efficiency of the system. Threads are implemented at the same time need to complete a number of tasks of the time.
The simplest analogy is like multi-threading for each carriage of the train, and the process is by train. The train left the carriage is not running, empathy can not be only one train carriage. Multithreading is to improve efficiency occurs. At the same time it appears also brought some problems.
The relationship between threads and processes:
An application process is executed on the processing of a process, it is a dynamic concept, and the thread is part of the process, the process contains multiple threads running. A program running at least one process, a process which contains at least one thread, the thread is an integral part of the process.
Simple to use 2.threading module:
Threading Import Import Time DEF Coding (): for the X-in the Range (3): Print ( ''re writing code ...') the time.sleep (1) DEF Drawing (): for the X-in the Range (3): Print ( ' Paint is% s'% threading.current_thread ()) # View thread the time.sleep (. 1) DEF main (): T1 = of the threading.Thread (= target Coding) # Create a thread T2 of the threading.Thread = (target = drawing) T1 .start () # start a thread t2.start () # Print (threading.enumerate ()) # View the number of threads with the name IF __name__ == '__main__': main ()
3. Thread class to create multiple threads:
In order to better encapsulation threaded code. Thread class may be used in the threading module inherits from the class, and then implement the run method. Thread will automatically run code run method.
import threading import time class CodingThread(threading.Thread): def run(self): for x in range(3): print('正在写代码%s' % threading.current_thread()) time.sleep(1) class DrawingThread(threading.Thread): def run(self): for x in range(3): print('正在画图%s' % threading.current_thread()) time.sleep(1) def main(): t1 = CodingThread() t2 = DrawingThread() t1.start() t2.start() if __name__ == '__main__': main()