-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi_thread.py
71 lines (53 loc) · 1.41 KB
/
multi_thread.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# encoding:utf-8
import threading
import time
# def greet(index):
# print 'hello world - %d' % index
# time.sleep(0.5)
#
#
# def line_run():
# for x in range(5):
# greet(x)
#
#
# def async_run():
# for x in range(5):
# th = threading.Thread(target=greet, args=[x])
# th.start()
import random
gLock = threading.Lock()
MONEY = 0
def producer():
while True:
global MONEY
random_money = random.randint(10, 100)
gLock.acquire()
MONEY += random_money
gLock.release()
print '生产者%s - 生产了:%d' % (threading.current_thread, random_money)
time.sleep(0.5)
def customer():
while True:
global MONEY
random_money = random.randint(10, 100)
if MONEY > random_money:
print '消费者%s - 消费了:%d' % (threading.current_thread, random_money)
gLock.acquire()
MONEY -= random_money
gLock.release()
else:
print '要消费: %d, 余额为: %d' % (random_money, MONEY)
time.sleep(0.5)
def p_c_test():
# 执行三个线程,作生产者
for x in range(3):
th = threading.Thread(target=producer)
th.start()
# 执行三个线程,作消费者
for x in range(3):
th = threading.Thread(target=customer)
th.start()
if __name__ == "__main__":
p_c_test()
# async_run()