1. Concurrent programming
- Implementing multiple tasks at the same time, often called "concurrent programming"
- There are 3 main ways to implement concurrent programming using Python: Multi-process, multi-threading, multi-process + multithreading.
- Inter-process communication must be shared through interprocess communication mechanisms (ipc,inter-process communication), including pipelines, signals, sockets, shared memory areas, and so on.
2. Single-Process thread
from random import randintfrom time import time, sleepdef download_task(filename): print(‘开始下载%s...‘ % filename) time_to_download = randint(5, 10) sleep(time_to_download) print(‘%s下载完成! 耗费了%d秒‘ % (filename, time_to_download))def main(): start = time() download_task(‘文件A.pdf‘) download_task(‘文件B‘) end = time() print(‘总共耗费了%.2f秒.‘ % (end - start))if __name__ == ‘__main__‘: main()
Inefficient, one file is downloaded and another file is downloaded
3. Put the download task into two processes (multi-process)
from multiprocessing import Processfrom os import getpidfrom random import randintfrom time import time, sleepdef download_task(filename): print(‘启动下载进程,进程号[%d].‘ % getpid()) print(‘开始下载%s...‘ % filename) time_to_download = randint(5, 10) sleep(time_to_download) print(‘%s下载完成! 耗费了%d秒‘ % (filename, time_to_download))def main(): start = time() p1 = Process(target=download_task, args=(‘文件A.pdf‘, )) p1.start() p2 = Process(target=download_task, args=(‘文件B.avi‘, )) p2.start() # 主程序主线程等待子进程p1, p2完成再继续执行 p1.join() p2.join() end = time() print(‘总共耗费了%.2f秒.‘ % (end - start))if __name__ == ‘__main__‘: main()
Python-Concurrent programming