Python的進程和線程,Python進程線程

來源:互聯網
上載者:User

Python的進程和線程,Python進程線程

進程:作業系統分配記憶體的一個基本單位,進程之間的記憶體是相互隔離的,如果進程間要相互連信,要靠一個IPC機制 process

線程:一個進程又可以劃分為多個線程,線程是進程的執行單元,也是作業系統分配CPU的基本單元  thread

為什麼要使用多進程和多線程?
如果一個任務執行時間很長,就可以分解成多線程或多進程,
提升執行效率,改善程式效能,縮短執行時間
改善使用者體驗,讓使用者獲得更好的使用者體驗


 

進程

multiprocessing模組提供了一個Process類來代表一個進程對象

import timefrom multiprocessing import Processimport oscount = 0def output(string):    global count    while count < 10:        print(string, end='', flush=True)        count += 1def main():    p1 = Process(target=output, args=('Ping', ))    p1.start()    p2 = Process(target=output, args=('Pong',))    p2.start()
多線程

多任務可以由多進程完成,也可以由一個進程內的多線程完成。

我們前面提到了進程是由若干線程組成的,一個進程至少有一個線程。

由於線程是作業系統直接支援的執行單元,因此,進階語言通常都內建多線程的支援,Python也不例外,並且,Python的線程是真正的Posix Thread,而不是類比出來的線程。

Python的標準庫提供了兩個模組:_thread和threading,_thread是低級模組,threading是進階模組,對_thread進行了封裝。絕大多數情況下,我們只需要使用threading這個進階模組。

啟動一個線程就是把一個函數傳入並建立Thread執行個體,然後調用start()開始執行

from threading import Threadcount = 0class PrintThread(Thread):    def __init__(self, string, count):        super().__init__()        self._string = string        self._count = count    def run(self):        for _ in range(self._count):            print(self._string, end='', flush=True)def main():    PrintThread('Ping', 10).start()    PrintThread('Pong', 10).start()

建立線程的兩種方式
1. 直接建立Thread對象並通過target參數指定線程啟動後要執行的任務
2. 繼承Thread自訂線程 通過重寫run方法指定線程啟動後執行的任務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.