Python - 並發編程

來源:互聯網
上載者:User

標籤:實現   技術   .com   共用記憶體   pre   開始   alt   沒有   單線程   

1. 並發編程
  1. 實現讓程式同時執行多個任務也就是常說的“並發編程”
  2. 使用Python實現並發編程主要有3種方式:多進程、多線程、多進程+多線程。
  3. 處理序間通訊必須通過處理序間通訊機制(IPC,Inter-Process Communication)來實現資料共用,具體的方式包括管道、訊號、通訊端、共用記憶體區等。
2. 單進程單線程
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()


沒有效率,一個檔案下載完,另一個檔案才下載

3. 把下載任務分別放到兩個進程中(多進程)
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 - 並發編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.