python生產者和消費者 threading

2021-10-06 10:24:07 字數 1789 閱讀 9108

from threading import thread,lock,condition

from queue import queue

import time

class

student

: count=

10mutex=

condition()

def produce_fun

(q):

while true:

with mutex:

while q.count>=10:

print

("生產者正在等待1秒"

) mutex.

wait()

q.count +=1

print

("生產者成功生產,當前數量為:"

+str

(q.count)

) mutex.

notifyall()

time.

sleep(1

)def consume_fun

(q,name)

:while true:

with mutex:

while q.count<=0:

print

("{}等待"

.format

(name)

) mutex.

wait()

q.count -=1

print

("{}正在消費,當前數量為:"

.format

(name)

+str

(q.count)

) mutex.

notifyall()

time.

sleep(1

)if __name__ ==

'__main__'

:# my_queue=queue(10)

# for index in range(10):

# my_queue.put(1)

s=student()

produce=

thread

(name=

"生產者"

,target=produce_fun,args=

(s,)

) consume1=

thread

(name=

"消費者"

,target=consume_fun,args=

(s,"消費者1"))

consume2 =

thread

(name=

"消費者"

, target=consume_fun, args=

(s,"消費者2"))

consume3 =

thread

(name=

"消費者"

, target=consume_fun, args=

(s,"消費者3"))

produce.

start()

consume1.

start()

consume2.

start()

consume3.

start()

produce.

join()

consume1.

join()

consume2.

join()

consume3.

join

()

python 生產者 消費者

from bs4 import beautifulsoup import requests import time import multiprocessing as mp import re from multiprocessing import queue from multiprocessin...

生產者消費者 生產者與消費者模式

一 什麼是生產者與消費者模式 其實生產者與消費者模式就是乙個多執行緒併發協作的模式,在這個模式中呢,一部分執行緒被用於去生產資料,另一部分執行緒去處理資料,於是便有了形象的生產者與消費者了。而為了更好的優化生產者與消費者的關係,便設立乙個緩衝區,也就相當於乙個資料倉儲,當生產者生產資料時鎖住倉庫,不...

生產者和消費者

package demo.one public class producerconsumerdemo 資源 class resource catch interruptedexception e this.name name count system.out.println thread.curre...