1. 程式人生 > >python 多進程,多線程,協程

python 多進程,多線程,協程

task return time finall ssi args 並且 python 代碼

在我們實際編碼中,會遇到一些並行的任務,因為單個任務無法最大限度的使用計算機資源。使用並行任務,可以提高代碼效率,最大限度的發揮計算機的性能。python實現並行任務可以有多進程,多線程,協程等方式。

進程,線程,協程

  • 進程

進程是程序運行的基本單位,資源分配和獨立運行的基本單位。

多進程實現並行任務代碼:

 import multiprocessing
 import time

 def test(interval):
     n = 5
     while n > 0:
         time.sleep(interval)
         n -= 1


 if __name__ == "__main__":
     p = multiprocessing.Process(target = test, args = (3,))
     p1 = multiprocessing.Process(target = test, args = (3,))
     p2 = multiprocessing.Process(target = test, args = (3,))
     p3 = multiprocessing.Process(target = test, args = (3,))

     p.start()
     p1.start()
     p2.start()
     p3.start()
     print("p.pid:", p.pid)
     print("p1.pid:", p.pid)
     print("p2.pid:", p.pid)
     print("p3.pid:", p.pid)

執行結果

技術分享圖片

  • 線程

通常在一個進程中可以包含若幹個線程,當然一個進程中至少有一個線程,不然沒有存在的意義。線程可以利用進程所擁有的資源,在引入線程的操作系統中,通常都是把進程作為分配資源的基本單位,而把線程作為獨立運行和獨立調度的基本單位,由於線程比進程更小,基本上不擁有系統資源,故對它的調度所付出的開銷就會小得多,能更高效的提高系統多個程序間並發執行的程度。

多線程實現並行(這裏采用線程池):

import threadpool
import threading
import time

task_pool = threadpool.ThreadPool(10)

def func(t):
    print(f‘sleep {t} s. {threading.currentThread()}‘)
    time.sleep(t)
    print(f‘{threading.currentThread()} have Done!!‘)

args = [5 for i in range(5)]
rs = threadpool.makeRequests(func, args)
for req in rs:
    task_pool.putRequest(req)
task_pool.wait()

運行結果
技術分享圖片

  • 協程

協程,又稱微線程,是為非搶占式多任務產生子程序的計算機程序組件,協程允許不同入口點在不同位置暫停或開始執行程序。
簡單來講,就是我們可以在執行的時候停下來執行另一子程序,當子程序執行完之後在此切換回來。並且是非阻塞的,也就意味著我們可以同時執行多個協程。
也因為協程是單線程,所以我們切換所需要的開銷最小,效率最高。

實現代碼:

import asyncio
import threading
import random

import time

async def test(t, count):
    print(f‘sleep {t} s. {threading.currentThread()}‘)
    # 使用asyncio.sleep() 而不用time.sleep() 是因為time.sleep()回掛起整個線程,
    # 而協程是基於單線程的,所以會block住
    #time.sleep(4)
    r = await asyncio.sleep(t)
    return t

def main():
    print("start ..")
    start =  time.time()
    loop = asyncio.get_event_loop()
    tasks = [test(1, i)  for i in range(5)]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
    print(f‘{time.time()-start}, finall {c}‘)
    return c

if __name__ == ‘__main__‘:
    x = main()

運行結果
技術分享圖片

python 多進程,多線程,協程