python 多任務回顧

 回顧一下 python的多任務

#coding=utf-8
import threading # 線程
import gevent # 協程
from time import sleep,ctime
from multiprocessing import Process  # 進程

from multiprocessing import Pool  # 進程池

from multiprocessing.dummy import Pool  #線程池
pool = Pool(5) #默認大小是cup的個數


import gevent.monkey
gevent.monkey.path_all()
from gevent.pool import Pool  #  協程池

def sing():
    for i in range(3):
        print("正在唱歌...%d"%i)
        sleep(1)

def dance():
    for i in range(3):
        print("正在跳舞...%d"%i)
        sleep(1)

if __name__ == '__main__':
    # 在python3中,主線程主進程結束,子線程,子進程不會結束,並且無序

    print('---開始---:%s'%ctime())
    t1 = threading.Thread(target=sing)
    t2 = threading.Thread(target=dance)


    # t1 = Process(target=sing)
    # t2 = Process(target=dance)
    t1.setDaemon(True)   # setDaemon(True) 主線程結束子線程立刻結束 如果多個子線程必須全部設置否則設置無效
    # t2.setDaemon(True)
    # t1.daemon=True       # daemon=True 主進程結束該子進程立刻結束
    # t2.daemon=True
    t1.start()
    t2.start()
    # t1.join()  #join 主進程(線程)阻塞,等待子進程(線程) 可以指定阻塞超時時間
    # t2.join()

    gevent.joinall([
        gevent.spawn(sing, "work1"),
        gevent.spawn(dance, "work2")
])

    #sleep(5) # 屏蔽此行代碼,試試看,程序是否會立馬結束?
    print('---結束---:%s'%ctime())

有錯誤請指正,謝謝

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章