python中的Lock

來源:互聯網
上載者:User

標籤:

 1 #Lock.py 2 from multiprocessing import Process,Lock 3 import os 4  5 def f(l,i): 6     l.acquire() 7     print(‘hello world %d and Ospid is %s...‘ %( i,os.getpid())) 8     l.release() 9 if __name__==‘__main__‘:10     lock = Lock()11     for num in range(10):12         Process(target=f,args=(lock,num)).start()

有Lock。

結果

 1 hello world 3 and Ospid is 4852... 2 hello world 2 and Ospid is 540... 3 hello world 0 and Ospid is 4160... 4 hello world 1 and Ospid is 948... 5 hello world 4 and Ospid is 5272... 6 hello world 6 and Ospid is 3100... 7 hello world 7 and Ospid is 3364... 8 hello world 8 and Ospid is 924... 9 hello world 9 and Ospid is 5196...10 hello world 5 and Ospid is 5460...

以下是無Lock

 1 #copy.py 2 __author__ = ‘liunnis‘ 3 from multiprocessing import Process,Lock 4 import os 5  6 def f(l,i): 7  8     print(‘hello world %d and Ospid is %s...‘ %( i,os.getpid())) 9 10 if __name__==‘__main__‘:11     lock = Lock()12     for num in range(10):13        p = Process(target=f,args=(lock,num))14        p.start()15 #       p.join()

結果:

 1 hello world 3 and Ospid is 944... 2 hello world 1 and Ospid is 4156... 3 hello world 8 and Ospid is 2136... 4 hello world 5 and Ospid is 3764... 5 hello world 6 and Ospid is 4876... 6 hello world 7 and Ospid is 4976... 7 hello world 2 and Ospid is 2640... 8 hello world 0 and Ospid is 1404... 9 hello world 9 and Ospid is 5748...10 hello world 4 and Ospid is 4032..

 

python中的Lock

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.