溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python多進程和多線程知識點整理

發布時間:2021-08-19 22:51:57 來源:億速云 閱讀:178 作者:chen 欄目:開發技術

這篇文章主要講解了“python多進程和多線程知識點整理”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“python多進程和多線程知識點整理”吧!

目錄
  • 多進程

  • 多線程

    • 線程安全

  • 高并發拷貝(多進程,多線程)

    說明

    相應的學習視頻見鏈接,本文只對重點進行總結。

    python多進程和多線程知識點整理

    python多進程和多線程知識點整理

    多進程

    重點(只要看下面代碼的main函數即可)

    1.創建

    2.如何開守護進程

    3.多進程,開銷大,用for循環調用多個進程時,后臺cpu一下就上去了

    import time
    import multiprocessing
    import os
    def dance(who,num):
        print("dance父進程:{}".format(os.getppid()))
        for i in range(1,num+1):
            print("進行編號:{}————{}跳舞。。。{}".format(os.getpid(),who,i))
            time.sleep(0.5)
    def sing(num):
        print("sing父進程:{}".format(os.getppid()))
        for i in range(1,num+1):
            print("進行編號:{}----唱歌。。。{}".format(os.getpid(),i))
            time.sleep(0.5)
    def work():
        for i in range(10):
            print("工作中。。。")
            time.sleep(0.2)
    if __name__ == '__main__':
        # print("main主進程{}".format(os.getpid()))
        start= time.time()
        #1 進程的創建與啟動
        # # 1.1創建進程對象,注意dance不能加括號
        # # dance_process = multiprocessing.Process(target=dance)#1.無參數
        # dance_process=multiprocessing.Process(target=dance,args=("lin",3))#2.以args=元祖方式
        # sing_process = multiprocessing.Process(target=sing,kwargs={"num":3})#3.以kwargs={}字典方式
        # # 1.2啟動進程
        # dance_process.start()
        # sing_process.start()
        #2.默認-主進程和子進程是分開的,主進程只要1s就可以完成,子進程要2s,主進程會等所有子進程執行完,再退出
        # 2.1子守護主進程,當主一但完成,子就斷開(如qq一關閉,所有聊天窗口就沒了).daemon=True
        work_process = multiprocessing.Process(target=work,daemon=True)
        work_process.start()
        time.sleep(1)
        print("主進程完成了!")#主進程和子進程是分開的,主進程只要1s就可以完成,子進程要2s,主進程會等所有子進程執行完,再退出
        print("main主進程花費時長:",time.time()-start)
        #

    多線程

    python多進程和多線程知識點整理

    重點

    1.創建

    2.守護線程

    3.線程安全問題(多人搶票,會搶到同一張)

    import time
    import os
    import threading
    def dance(num):
        for i in range(num):
            print("進程編號:{},線程編號:{}————跳舞。。。".format(os.getpid(),threading.current_thread()))
            time.sleep(1)
    def sing(count):
        for i in range(count):
            print("進程編號:{},線程編號:{}----唱歌。。。".format(os.getpid(),threading.current_thread()))
            time.sleep(1)
    def task():
        time.sleep(1)
        thread=threading.current_thread()
        print(thread)
    if __name__ == '__main__':
        # start=time.time()
        # # sing_thread =threading.Thread(target=dance,args=(3,),daemon=True)#設置成守護主線程
        # sing_thread = threading.Thread(target=dance, args=(3,))
        # dance_thread = threading.Thread(target=sing,kwargs={"count":3})
        #
        # sing_thread.start()
        # dance_thread.start()
        #
        # time.sleep(1)
        # print("進程編號:{}主線程結束...用時{}".format(os.getpid(),(time.time()-start)))
        for i in range(10):#多線程之間執行是無序的,由cpu調度
            sub_thread = threading.Thread(target=task)
            sub_thread.start()

    線程安全

    由于線程直接是無序進行的,且他們共享同一個進程的全部資源,所以會產生線程安全問題(比如多人在線搶票,買到同一張)

    python多進程和多線程知識點整理
    python多進程和多線程知識點整理

    #下面代碼在沒有lock鎖時,會賣出0票,加上lock就正常

    import threading
    import time
    lock =threading.Lock()
    class Sum_tickets:
        def __init__(self,tickets):
            self.tickets=tickets
    def window(sum_tickets):
        while True:
            with lock:
                if sum_tickets.tickets>0:
                    time.sleep(0.2)
                    print(threading.current_thread().name,"取票{}".format(sum_tickets.tickets))
                    sum_tickets.tickets-=1
                else:
                    break
    if __name__ == '__main__':
        sum_tickets=Sum_tickets(10)
        sub_thread1 = threading.Thread(name="窗口1",target=window,args=(sum_tickets,))
        sub_thread2 = threading.Thread(name="窗口2",target=window,args=(sum_tickets,))
        sub_thread1.start()
        sub_thread2.start()

    高并發拷貝(多進程,多線程)

    import os
    import multiprocessing
    import threading
    import time
    def copy_file(file_name,source_dir,dest_dir):
        source_path = source_dir+"/"+file_name
        dest_path =dest_dir+"/"+file_name
        print("當前進程為:{}".format(os.getpid()))
        with open(source_path,"rb") as source_file:
            with open(dest_path,"wb") as dest_file:
                while True:
                    data=source_file.read(1024)
                    if data:
                        dest_file.write(data)
                    else:
                        break
        pass
    if __name__ == '__main__':
        source_dir=r'C:\Users\Administrator\Desktop\注意力'
        dest_dir=r'C:\Users\Administrator\Desktop\test'
        start = time.time()
        try:
            os.mkdir(dest_dir)
        except:
            print("目標文件已存在")
        file_list =os.listdir(source_dir)
        count=0
        #1多進程
        for file_name in file_list:
            count+=1
            print(count)
            sub_processor=multiprocessing.Process(target=copy_file,
                                    args=(file_name,source_dir,dest_dir))
            sub_processor.start()
            # time.sleep(20)
        print(time.time()-start)
    #這里有主進程和子進程,通過打印可以看出,主進程在創建1,2,3,4,,,21過程中,子進程已有的開始執行,也就是說,每個進程是互不影響的
    # 9
    # 10
    # 11
    # 12
    # 13
    # 當前進程為:2936(當主進程創建第13個時,此時,第一個子進程開始工作)
    # 14
    # 當前進程為:10120
    # 當前進程為:10440
    # 15
    # 當前進程為:9508
        # 2多線程
        # for file_name in file_list:
        #     count += 1
        #     print(count)
        #     sub_thread = threading.Thread(target=copy_file,
        #                                             args=(file_name, source_dir, dest_dir))
        #     sub_thread.start()
        #     # time.sleep(20)
        # print(time.time() - start)

    感謝各位的閱讀,以上就是“python多進程和多線程知識點整理”的內容了,經過本文的學習后,相信大家對python多進程和多線程知識點整理這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

    向AI問一下細節

    免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

    AI

    亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女