Python-Concurrent programming

Source: Internet
Author: User

1. Concurrent programming
  1. Implementing multiple tasks at the same time, often called "concurrent programming"
  2. There are 3 main ways to implement concurrent programming using Python: Multi-process, multi-threading, multi-process + multithreading.
  3. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.