python线程操作中的锁,先获取,执行临界区代码,释放锁。
如果在获取到锁之后,释放锁执行的代码中,出现了IO操作,或者sleep操作,均会导致锁失效,临界区代码执行不可控。
以下为例:
import sys
import os
import time
import thread,threading
g_count = 0
g_lock = thread.allocate_lock()
def hello(name):
global g_count,g_lock
g_lock.acquire() ##获取锁
for i in range(0, 10):
g_count = g_count + 1
print name + str(g_count)
time.sleep(1) ##该语句将会导致线程锁失效,和没加锁的情况是一样的。临界区代码控制失去意义。若有IO操作也是同样。
g_lock.release() ##释放锁
t1 = thread.start_new_thread(hello, ('thread1-',))
t2 = thread.start_new_thread(hello, ('thread2-',))
time.sleep(5)
如果将上述代码中获取锁、释放锁的代码注释,打印的将会线程1、线程2的交错,两个进程分别随机的获取时间片。
而有锁的情况下, 会在临界区代码被一个线程执行结束之后,另外一个进程可入。