1
2
3
4
5
|
第一步:线程A修改了num的值为
7
第二步:线程C不知道num的值已经发生了改变,直接调用了num的值
7
第三步:线程B对num值加
1
,此时num值变为
8
第四步:线程B使用了num值
8
第五步:线程A使用了num值
8
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
threading
import
time
number =
0
def run(num):
global number
number +=
1
print number
time.sleep(
1
)
for
i
in
range(
20
):
t = threading.Thread(target=run, args=(i,))
t.start()
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day6$ python thread_clock6.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
threading
import
time
number =
0
lock = threading.RLock() #调用threading模块中的RLock()
def run(num):
lock.acquire() #开始给线程加锁
global number
number +=
1
lock.release() #给线程解锁
print number
time.sleep(
1
)
for
i
in
range(
20
):
t = threading.Thread(target=run, args=(i,))
t.start()
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day6$ python thread_clock6.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
threading
import
time
number =
0
lock = threading.RLock()
def run(num):
lock.acquire()
global number
number +=
1
print number
time.sleep(
1
) #把time.sleep(
1
)也锁在线程中
lock.release()
for
i
in
range(
20
):
t = threading.Thread(target=run, args=(i,))
t.start()
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day6$ python thread_clock6.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
1
2
3
4
5
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day6$ time python thread_clock6.py | grep
'real'
real 0m20.073s
user 0m0.024s
sys 0m0.008s
|