1 测试1
2
3 import threading
4 import time
5
6 g_num = 0
7
8 def work1(num):
9 global g_num
10 for i in range(num):
11 g_num += 1
12 print("----in work1, g_num is %d---"%g_num)
13
14
15 def work2(num):
16 global g_num
17 for i in range(num):
18 g_num += 1
19 print("----in work2, g_num is %d---"%g_num)
20
21
22 print("---线程创建之前g_num is %d---"%g_num)
23
24 t1 = threading.Thread(target=work1, args=(100,))
25 t1.start()
26
27 t2 = threading.Thread(target=work2, args=(100,))
28 t2.start()
29
30 while len(threading.enumerate()) != 1:
31 time.sleep(1)
32
33 print("2个线程对同一个全局变量操作之后的最终结果是:%s" % g_num)
34 运行结果:
35
36 ---线程创建之前g_num is 0---
37 ----in work1, g_num is 100---
38 ----in work2, g_num is 200---
39 2个线程对同一个全局变量操作之后的最终结果是:200
-----------------------------------------------------------------------------------
40 测试2
41
42 import threading
43 import time
44
45 g_num = 0
46
47 def work1(num):
48 global g_num
49 for i in range(num):
50 g_num += 1
51 print("----in work1, g_num is %d---"%g_num)
52
53
54 def work2(num):
55 global g_num
56 for i in range(num):
57 g_num += 1
58 print("----in work2, g_num is %d---"%g_num)
59
60
61 print("---线程创建之前g_num is %d---"%g_num)
62
63 t1 = threading.Thread(target=work1, args=(1000000,))
64 t1.start()
65
66 t2 = threading.Thread(target=work2, args=(1000000,))
67 t2.start()
68
69 while len(threading.enumerate()) != 1:
70 time.sleep(1)
71
72 print("2个线程对同一个全局变量操作之后的最终结果是:%s" % g_num)
73 运行结果:
74
75 ---线程创建之前g_num is 0---
76 ----in work1, g_num is 1088005---
77 ----in work2, g_num is 1286202---
78 2个线程对同一个全局变量操作之后的最终结果是:1286202
79 结论
80
81 如果多个线程同时对同一个全局变量操作,会出现资源竞争问题,从而数据结果会不正确