[Reptile] Load version of the producer and consumer model

'''
Lock version Producer and consumer model
'''

import threading
import random
import time

gMoney < /span>= 1000 # Original amount
gLoad = threading.Lock()
gTime
= 0 # production times

class Producer(threading.Thread):
def run(self):
global gMoney
global gTime
while True:
gLoad.acquire()
if gTime <20:
gTime
+= 1
money
= random.randint(50,500)
gMoney
+= money
print("The production thread %s generated %d yuan, and the remaining %d yuan"%(threading.current_thread(),money,gMoney))
else :
gLoad.release()
break
gLoad.release()
time.sleep (
1)


class Consumer(threading.Thread):
def run(self):
global gMoney
span>while True:
gLoad.acquire()
money
= random.randint(50,500)
if money > gMoney:
print("%s thread ends, need to consume %d, principal is %d "%(threading.current_thread(), money, gMoney))
gLoad.release()< br />
break
else:
gMoney
-= money
print span>("The consumer thread %s consumed %d yuan, and the remaining %d yuan" % (threading.current_thread(), money, gMoney))
gLoad.release()
time.sleep(
1)


def main():
for x in range(5):
t
= Producer(name="producer thread%s"%x)
t.start()

for x in range(3):
t
= Consumer(name="Consumer thread%s"%x)
t.start()


if __name__ == '__main__':
main ()

'''
The producer and consumer model of the Lock version
'''


import threading
import random
import time

gMoney
= 1000 # Original amount
gLoad = threading.Lock()
gTime
= 0 # Production times

class Producer(threading.Thread):
def run(self):
global gMoney
global gTime
while True:
gLoad.acquire()
if gTime <20:
gTime
+= 1
money
= random.randint(50,500)
gMoney
+= money
print("Production thread %s generated %d yuan and the remaining %d yuan"%(threading.current_thread() ,money,gMoney))
else:
gLoad.release( )
break
gLoad.release()
time .sleep(
1)


class Consumer(threading.Thread):
def run (self):
global gMoney
while True:
gLoad.acquire()
money
= random.randint( 50,500)
if money > gMoney:
print("%s thread ends, need to consume %d, principal is %d"%(threading.current_thread(), money, gMoney))
gLoad.release()
break
else:
gMoney
-= money
print( "The consumer thread %s consumed %d yuan, and the remaining %d yuan" % (threading.current_thread(), money, gMoney))
gLoad.release()
time. sleep(
1)


def main():
for x in range(5):
t
= Producer(name="< /span>Producer thread%s"%x)
t.start()

for x in range(3):
t
= Consumer(name="Consumer thread %s"%x)
t.start()


if < span style="color: #800080">__name__
== '__main__< span style="color: #800000">':
main()

< /p>

Leave a Comment

Your email address will not be published.