File tree Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ import _thread
2
+ import time
3
+ '''
4
+ Python 3.X _thread 模块演示 Demo
5
+ 当注释掉 self.lock.acquire() 和 self.lock.release() 后运行代码会发现最后的 count 为 467195 等,并发问题。
6
+ 当保留 self.lock.acquire() 和 self.lock.release() 后运行代码会发现最后的 count 为 1000000,锁机制保证了并发。
7
+ time.sleep(5) 就是为了解决 _thread 模块的诟病,注释掉的话子线程没机会执行了
8
+ '''
9
+ class ThreadTest (object ):
10
+ def __init__ (self ):
11
+ self .count = 0
12
+ self .lock = None
13
+
14
+ def runnable (self ):
15
+ self .lock .acquire ()
16
+ print ('thread ident is ' + str (_thread .get_ident ())+ ', lock acquired!' )
17
+ for i in range (0 , 100000 ):
18
+ self .count += 1
19
+ print ('thread ident is ' + str (_thread .get_ident ()) + ', pre lock release!' )
20
+ self .lock .release ()
21
+
22
+ def test (self ):
23
+ self .lock = _thread .allocate_lock ()
24
+ for i in range (0 , 10 ):
25
+ _thread .start_new_thread (self .runnable , ())
26
+
27
+ if __name__ == '__main__' :
28
+ test = ThreadTest ()
29
+ test .test ()
30
+ print ('thread is running...' )
31
+ time .sleep (5 )
32
+ print ('test finish, count is:' + str (test .count ))
You can’t perform that action at this time.
0 commit comments