Why multitasking? What are the benefits?
A: improve the efficiency of program execution, and achieve more than two things at the same time.
La La La... The key is coming.
Parallel: if the number of tasks is less than the number of CPU cores, each CPU will execute multiple tasks. Then it must be busy. Multiple tasks need to be queued to wait for the last task to finish before the next task can be executed.
Concurrency: when the number of tasks is less than or equal to the number of CPU cores, only one task is needed for each CPU (when less than, some CPUs do not perform tasks).
1. Thread: the minimum unit of CPU scheduling. My understanding is the clue that the CPU executes the code.
Create thread:
1 import threading 2 3 4 def f1(): 5 for i in range(100): 6 print('Thread 1:{}'.format(i)) 7 8 9 def f2(): 10 for i in range(100): 11 print('Thread 2:{}'.format(i)) 12 13 14 if __name__ == '__main__': 15 t1 = threading.Thread(target=f1) 16 t2 = threading.Thread(target=f2) 17 t1.start() 18 t2.start()
As a result, threads compete for resources.
2. Process: the minimum unit of CPU allocated resources. My understanding is that when the program is running, the resources used by code + running are the process. The process has three states: ready state (waiting for CPU to execute if all conditions are met), waiting state (blocking waiting such as input(),accept(),yield, etc.), executing state (CPU is executing its functions)
Create process:
1 from multiprocessing import Process 2 3 4 def f1(msg): 5 for i in range(100): 6 print(msg + ': {}'.format(i)) 7 8 9 def f2(msg): 10 for i in range(100): 11 print(msg + ': {}'.format(i)) 12 13 14 if __name__ == '__main__': 15 p1 = Process(target=f1, args=('Thread 1',)) 16 p2 = Process(target=f2, args=('Thread 2',)) 17 p1.start() 18 p2.start()
3. Co process: CO process is another way to implement multitasking in python, but it occupies smaller execution unit (understood as required resources) than thread.
To create a process:
1 import time 2 3 4 def fn1(): 5 while True: 6 print("----Task 1-----") 7 yield 8 time.sleep(1) 9 10 11 def fn2(): 12 while True: 13 print("----Task 2-----") 14 yield 15 16 17 def main(): 18 work1 = fn1() 19 work2 = fn2() 20 21 while True: 22 next(work1) 23 next(work2) 24 25 26 if __name__ == "__main__": 27 main()