One, multi-process and multi-threading
Common:
Allow multiple CPUs to process requests at the same time
Difference:
1. Threads in multiple threads are shared on memory space, and processes and processes use different memory spaces. That is, creating a thread does not need to open up memory space, and creating a new process requires allocating new memory space for it
Global interpreter Lock (GIL)
In each process the "exit" is unique to Python. Its role is: to achieve the 1 limit, what restrictions, if there are 2 threads are scheduled at the same time, the global interpreter lock limit can only have 1 through the global interpreter lock, can be CPU scheduling
When should you use multiple processes and when should I use multithreading?
- Multithreading for I/O intensive
- Compute intensive Multi-process
Other ways to thread objects:
- Start thread is ready to wait for CPU scheduling
- SetName setting a name for a thread
- GetName Get thread Name
- Setdaemon (True/false) True is set to background thread (default is set to False, that is, the set foreground thread is not written)
if it is a background thread, during the main thread execution, the background thread is also in progress, and after the main thread finishes executing, the background thread stops regardless of success or not.
If it is the foreground thread, during the main thread execution, the foreground thread is also in progress, and after the main thread finishes executing, wait for the foreground thread to finish, the program stops
- The join executes each thread one by one and continues execution after execution, making multithreading meaningless
- Run method that executes the thread class object after the run thread is dispatched by the CPU
One, thread example 1
thread1.py
#!/usr/bin/env python#-*-coding:utf-8-*-import threadingimport timedef Show (ARG): time.sleep (1) print ' Thread ' +str (ARG) for I in range: #创建1个线程, execute the Show method, receive 1 parameters T = Threading. Thread (target=show,args= (i)) #t. Setdaemon (True) #主线程执行完成之后, close
print ' main thread stop '
thread2.py
#!/usr/bin/env python#-*-coding:utf-8-*-import threadingimport timedef Show (ARG): time.sleep (1) print ' Thread ' +str (ARG) for I in range: #创建1个线程, execute the Show method, receive 1 parameters T = Threading. Thread (target=show,args= (i,))
#设置为后台线程, the main thread is closed immediately after execution
T.start ()
print ' main thread stop '
Execute the thread1.py and produce the following results:
Execute the thread2.py and produce the following results:
The thread, process, and path of the Python development