[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>

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 2008 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.