python 程序 鎖 佇列

2021-10-08 14:27:48 字數 3278 閱讀 1602

######程序

from multiprocessing import process

import os

deffunc

(a,b)

:print

(os.getpid(

),os.getppid(

),a,b)

#pid子程序 ppid父程序

if __name__ ==

"__main__"

:print

('main:'

,os.getpid(

),os.getppid())

p = process(target=func,args=

('aa',7

))p.start(

)###併發

from multiprocessing import process

import os

import time

deffunc()

: time.sleep(1)

print

(os.getpid(

),os.getppid())

if __name__ ==

"__main__"

:print

('main:'

,os.getpid(

),os.getppid())

for i in

range(10

):p = process(target=func)

p.start(

)####守護程序

from multiprocessing import process

import time

deffunc1()

:while

true

:print

('--->in fun1'

) time.sleep(1)

deffunc2()

:for i in

range(5

):print

('---->func2'

)if __name__ ==

"__main__"

: p1 = process(target=func1)

p1.daemon =

true

#表示p1是乙個守護程序,守護程序會在主程序結束**的時候結束。

p1.start(

) p2 = process(target=func2)

time.sleep(3)

p2.start(

)print

('_in main_'

)#主程序會等待所有子程序結束,是為了**子程序的資源

########鎖

from multiprocessing import process,lock

import time

import json

defquery

(i):

with

open

('src/task'

,'r'

,encoding=

'utf-8'

)as f:

file

= json.load(f)

print

(f":還有票"

)def

buyticket

(i):

with

open

('src/task'

,'r'

,encoding=

'utf-8'

)as f:

file

= json.load(f)

iffile

['ticket'

]>0:

print

(f'買到票了'

)file

['ticket']-=

1 time.sleep(

0.1)

#為了模擬網路中所耗的時間

with

open

('src/task'

,'w'

,encoding=

'utf-8'

)as f:

json.dump(

file

,f)def

main

(i,lock)

: query(i)

lock.acquire(

)#拿鑰匙

buyticket(i)

lock.release(

)#還鑰匙

if __name__ ==

'__main__'

: l = lock(

)for i in

range(5

):p = process(target=main,args=

(i,l)

) p.start(

)#######佇列

from multiprocessing import queue,process

import time

import random

defconsumers

(q,name)

:for i in

range(10

):print

(f"吃了"

)def

produce

(q,name,food)

:for i in

range(5

):foodi =

'%s%s'

%(food,i)

print

(f"生產了"

) time.sleep(random.random())

q.put(foodi)

if __name__ ==

"__main__"

: q = queue(

) c = process(target=consumers,args=

(q,'cc'))

p1 = process(target=produce,args=

(q,'test1'

,'西瓜汁'))

p2 = process(target=produce,args=

(q,'test2'

,'蘋果汁'))

c.start(

) p1.start(

) p2.start(

) p1.join(

) p2.join(

)

Python程序相關(二)互斥鎖 程序佇列

互斥鎖 對於模擬多人查票搶票 票數放在檔案中db.txt 程式 from multiprocessing import process import json import time import random import os def search time.sleep random.randi...

程序鎖(互斥鎖)(Python)

3 搶票示例 import json import time from multiprocessing import process,lock defsearch i with open ticket encoding utf 8 as f ticket json.load f print s 當前...

python執行緒鎖 守護執行緒,程序鎖 守護程序

1 守護程序 1.1 什麼是守護程序?1 守護程序會在主程序 執行結束的情況下,立即結束。2 守護程序本身其實就是乙個子程序。3 主程序在其 結束後已經執行完畢 守護程序在此時就被 然後主程序會一直等非守護的子程序都執行完畢後 子程序的資源才會結束。1.2 為什麼要用守護程序?1 守護程序本身就是乙...