天天看點

python—多線程

一、多線程執行個體

  線程時應用程式中工作的最小機關,python中提供了threading子產品來對多線程操作,一般多核cpu采用多程序方式,單核才采用多線程方式

  方法:

  将要執行的方法threading.Thread作為參數傳給構造方法(和多程序類似),格式如下:

  t = threading.Thread(target=action,args=(i,))

例子:

運作結果:

start worker1

start worker2

start worker3

start worker4

start worker5

start Mythread 6

start Mythread 7

start Mythread 8

start Mythread 9

start Mythread 10

擴充:super()方法的文法: super(type[, object-or-type]);type -- 類名,object-or-type --對象或類型,一般為self

例子:

Parent

Child

************************

hello China I'm parent

I'm child

Good

二、線程鎖

  通過threading.Lock()來建立鎖,函數在執行前先獲得鎖,執行後釋放鎖,和程序鎖相似

  with lock:

  或者

  lock.acquire()  #先獲得鎖

  ...

  lock.release()  #執行完,釋放鎖

main end

end worker1

end worker2

說明:隻有線程1結束以後,線程2才能執行

三、線程共享變量

  多線程和多程序不同之處在于多線程本身就是可以和父程序進行共享記憶體的,這也是為什麼其中一個線程挂掉之後,其他線程也死掉的原因

[1, 2, 3, 4]

[1, 2, 3, 4, 'hello', 'china', 'world']