-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.py
More file actions
58 lines (46 loc) · 1.17 KB
/
thread.py
File metadata and controls
58 lines (46 loc) · 1.17 KB
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
import os
def foo1():
print('Process (%s) start...' % os.getpid())
# only work on Unix/Linux/Mac
pid = os.fork()
if pid == 0:
print('i am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))
else:
print('i (%S) just create a child process(%s).' % (os.getpid, pid))
return True
import time, threading
# 假定这是你的银行存款:
balance = 0
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(100000):
change_it(n)
# t1 = threading.Thread(target=run_thread, args=(5,))
# t2 = threading.Thread(target=run_thread, args=(8,))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# print(balance)
balance = 0
lock = threading.Lock()
def runthread(n):
for i in range(100000):
# lock
lock.acquire()
try:
change_it(n)
finally:
lock.release()
if __name__ == '__main__':
t1 = threading.Thread(target=runthread, args=(5,))
t2 = threading.Thread(target=runthread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)