python---线程与进程
一 線程
1.1 概述
線程是操作系統能夠進行運算調度的最小單位。它被包含在進程之中,是進程中的實際運作單位。一條線程指的是進程中一個單一順序的控制流,一個進程中可以并發多個線程,每條線程并行執行不同的任務。
Threading用于提供線程相關的操作:
import threading import timedef show(arg):time.sleep(1)print ('thread'+str(arg))for i in range(10):t = threading.Thread(target=show, args=(i,))t.start()print ('main thread stop')>>>main thread stop >>>thread0 >>>thread6 >>>thread3 >>>thread2 >>>thread5 >>>thread4 >>>thread1 >>>thread7 >>>thread8 >>>thread9上述代碼創建了10個“前臺”線程,然后控制器就交給了CPU,CPU根據指定算法進行調度,分片執行指令。
注:后臺線程行為: 只要你的主線程執行完畢了,后臺線程,不管你執行到哪里了,就直接關閉了。前臺線程行為: 主程序執行過程中,前臺線程也在執行,主程序執行完畢后,等待前臺線程也執行完成后,程序結束。
start #線程準備就緒,等待CPU調度 setName #為線程設置名稱 getName #獲取線程名稱 setDaemon #設置為后臺線程或前臺線程(默認),如果是后臺線程,主線程執行過程中,后臺線程也在進行,主線程執行完畢后,后臺線程不論成功與否,均停止 如果是前臺線程,主線程執行過程中,前臺線程也在進行,主線程執行完畢后,等待前臺線程也執行完成后,程序停止 join #逐個執行每個線程,執行完畢后繼續往下執行,該方法使得多線程變得無意義 run #線程被cpu調度后自動執行線程對象的run方法 更多方法1.2 線程鎖(Lock,RLock)
由于線程之間是進行隨機調度,并且每個線程可能只執行n條執行之后,當多個線程同時修改同一條數據時可能會出現臟數據,所以,出現了線程鎖 - 同一時刻允許一個線程執行操作。
import threading import timegl_num = 0def show(arg):global gl_numtime.sleep(1)gl_num +=1print (gl_num,end=' ')for i in range(10):t = threading.Thread(target=show, args=(i,))t.start()print ('main thread stop')>>>main thread stop >>>1 2 3 4 5 6 7 8 9 10 未使用鎖 import threading import timegl_num = 0lock = threading.RLock()def Func():lock.acquire()global gl_numgl_num +=1time.sleep(1)print (gl_num)lock.release()for i in range(10):t = threading.Thread(target=Func)t.start() 線程鎖1.3 信號量(semaphore)
多線程編程的最常見問題是數據共享。當多個線程都修改某一個共享數據的時候,需要進行同步控制。線程同步能夠保證多個線程安全訪問競爭資源,最簡單的同步機制是引入互斥鎖。互斥鎖為資源引入一個狀態:鎖定/非鎖定。某個線程要更改共享數據時,先將其鎖定,此時資源的狀態為“鎖定”,其他線程不能更改;直到該線程釋放資源,將資源的狀態變成“非鎖定”,其他的線程才能再次鎖定該資源。互斥鎖保證了每次只有一個線程進行寫入操作,從而保證了多線程情況下數據的正確性。
而互斥鎖 同時只允許一個線程更改數據,而Semaphore是同時允許一定數量的線程更改數據 ,比如廁所有3個坑,那最多只允許3個人上廁所,后面的人只能等里面有人出來了才能再進去。
import threading,timedef run(n):semaphore.acquire()time.sleep(2)print("run the thread: %s" %n)semaphore.release()if __name__ == '__main__':num= 0semaphore = threading.BoundedSemaphore(5) #最多允許5個線程同時運行for i in range(20):t = threading.Thread(target=run,args=(i,))t.start()1.4 事件(event)
python線程的事件用于主線程控制其他線程的執行,事件主要提供了三個方法?set、wait、clear。事件處理的機制:全局定義了一個“Flag”,clear將“Flag”設置為False,set將“Flag”設置為True。如果“Flag”值為 False,那么當程序執行 event.wait 方法時就會阻塞,如果“Flag”值為True,那么event.wait 方法時便不再阻塞。
import threadingdef do(event):print ('start')event.wait()print ('execute')event_obj = threading.Event() for i in range(10):t = threading.Thread(target=do, args=(event_obj,))t.start()event_obj.clear() inp = input('input:') if inp == 'true':event_obj.set()1.5 timer
定時器,指定n秒后執行某操作
from threading import Timerdef hello():print("hello, world")t = Timer(1, hello) t.start() # after 1 seconds, "hello, world" will be printed二 進程
2.1 進程的創建
from multiprocessing import Process import timedef worker(interval):n = 5while n > 0:print("The time is {0}".format(time.ctime()))time.sleep(interval)n -= 1if __name__ == "__main__":p = Process(target = worker, args = (3,))p.start()print ("p.pid:", p.pid)print ("p.name:", p.name)print ("p.is_alive:", p.is_alive())>>>p.pid: 5360 >>>p.name: Process-1 >>>p.is_alive: True >>>The time is Thu Jul 12 18:57:23 2018 >>>The time is Thu Jul 12 18:57:26 2018 >>>The time is Thu Jul 12 18:57:29 2018 >>>The time is Thu Jul 12 18:57:32 2018 >>>The time is Thu Jul 12 18:57:35 2018 單進程 import multiprocessing import timedef worker_1(interval):print ("worker_1")time.sleep(interval)print ("end worker_1")def worker_2(interval):print ("worker_2")time.sleep(interval)print ("end worker_2")def worker_3(interval):print ("worker_3")time.sleep(interval)print ("end worker_3")if __name__ == "__main__":p1 = multiprocessing.Process(target = worker_1, args = (2,))p2 = multiprocessing.Process(target = worker_2, args = (3,))p3 = multiprocessing.Process(target = worker_3, args = (4,))p1.start()p2.start()p3.start()print("The number of CPU is:" + str(multiprocessing.cpu_count()))for p in multiprocessing.active_children():print("child p.name:" + p.name + "\tp.id" + str(p.pid))print ("END!!!!!!!!!!!!!!!!!")>>>The number of CPU is:4 >>>child p.name:Process-1 p.id5196 >>>child p.name:Process-2 p.id8680 >>>child p.name:Process-3 p.id2732 >>>END!!!!!!!!!!!!!!!!! >>>worker_2 >>>worker_1 >>>worker_3 >>>end worker_1 >>>end worker_2 >>>end worker_3 多進程注意:(1)由于進程之間的數據需要各自持有一份,所以創建進程需要的非常大的開銷。
(2)進程各自持有一份數據,默認無法共享數據
2.2?daemon
子進程設置了daemon屬性時,主進程結束,它們就隨著結束了。(線程也有deamon操作)
import multiprocessing import timedef worker(interval):print("work start:{0}".format(time.ctime()));time.sleep(interval)print("work end:{0}".format(time.ctime()));if __name__ == "__main__":p = multiprocessing.Process(target = worker, args = (3,))p.start()print ("end!")>>>end! >>>work start:Thu Jul 12 19:12:51 2018 >>>work end:Thu Jul 12 19:12:54 2018 不加deamon import multiprocessing import timedef worker(interval):print("work start:{0}".format(time.ctime()));time.sleep(interval)print("work end:{0}".format(time.ctime()));if __name__ == "__main__":p = multiprocessing.Process(target = worker, args = (3,))p.daemon = Truep.start()print ("end!")>>>end! 有deamon?參考:https://www.cnblogs.com/yuanchenqi/articles/5733873.html
https://www.cnblogs.com/wupeiqi/articles/5040827.html
轉載于:https://www.cnblogs.com/Terrypython/p/9301428.html
總結
以上是生活随笔為你收集整理的python---线程与进程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成都车展新车抢先看:混动本田思域领衔、还
- 下一篇: 宏光MINIEV GAMEBOY限量版发