Reptile 19- producers and consumers and the queue thread

import threading
import random
import time

gMoney = 1000
gLock = threading.Lock()
gTotalTimes = 10
gTimes = 0


class Producer(threading.Thread):
    def run(self):
        global gMoney
        global gTimes
        while True:
            money = random.randint(100,1000)
            gLock.acquire()
            if gTimes >= gTotalTimes:
                gLock.release()
                break
            gMoney += money
            print('%s生产了%d元钱,剩余%d元钱'%(threading.current_thread(),money,gMoney))
            gTimes += 1
            gLock.release()
            the time.sleep (0.5)


Consumer class (of the threading.Thread): 
    DEF RUN (Self): 
        Global gMoney 
        the while True: 
            Money the random.randint = (100,1000) 
            gLock.acquire () 
            IF gMoney> = Money: 
                gMoney - = Money 
                Print ( '% S Consumption % d dollars were consumed, the remaining dollars% d '% (threading.current_thread (), Money, gMoney)) 
            the else: 
                IF gTimes> = gTotalTimes: 
                    gLock.release () 
                    BREAK 
                Print ('% S consumer is ready to consume dollars% d,% d remaining dollars, less than '% (threading.current_thread (), Money, gMoney))! 
            gLock.release () 
            the time.sleep (0.5) 
    for X in Range (. 3) :


main DEF (): 
        T = Consumer (name = 'D consumer thread%'% X) 
        t.start () 

    for X in Range (. 5): 
        T = Producer (name = "producer thread% d"% x) 
        t.start () 

IF the __name__ == '__main__': 
    main ()

  

 

from queue import Queue
import threading
import time
def test():

    q = Queue(4)
    for i in range(4):
        q.put(i)

    for i in range(4):
        print(q.get())
    print(q.full())
    print(q.empty())
    print(q.qsize())

def set_value(q):
    index=0
    while True:
        q.put(index)
        index+=1
        time.sleep(1)

def get_value(q):
    while True:
        print(q.get())

def main():
    q=Queue(4)
    t1=threading.Thread(target=set_value,args=[q])
    t2=threading.Thread(target=get_value,args=[q])

    t1.start()
    t2.start()

if __name__ == '__main__':
    main()

  

Guess you like

Origin www.cnblogs.com/wcyMiracle/p/12500007.html