我是一个尝试理解Python线程模块的菜鸟。我正在使用Python 2.7版本。其中一个使用with语句的动机是代码模式。
产生以下输出:
请帮助我理解为什么使用with语句时锁定不起作用,或者我完全误解了这个概念。即使定义了锁,我也不明白为什么会直接进入print("Exiting main thread")。
with threading.Lock():
//User defined function in a new thread
我不确定我是否正确理解了它,但我的初步假设是这段代码应该在主线程上获取锁,一旦子线程完成后就会释放该锁。然而,这个脚本
from __future__ import print_function
import threading
import time
import functools
#import contextlib
#Thread module for dealing with lower level thread operations.Thread is limited use Threading instead.
def timeit(fn):
'''Timeit function like this doesnot work with the thread calls'''
def wrapper(*args,**kwargs):
start = time.time()
fn(*args,**kwargs)
end = time.time()
threadID = ""
print ("Duration for func %s :%d\n"%(fn.__name__ +"_"+ threading.current_thread().name ,end-start))
return wrapper
exitFlag = 0
@timeit
def print_time(counter,delay):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print("%s : %s_%d"%(threading.current_thread().name,time.ctime(time.time()),counter))
counter -= 1
class Mythread(threading.Thread):
def __init__(self,threadID,name,counter,delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.delay = delay
def run(self):
print("Starting%s\n" % self.name)
print_time(self.counter, self.delay)
print("Exiting%s\n" % self.name)
if __name__ == '__main__':
'''
print_time(5, 1)
threadLock = threading.Lock()
threads = []
thread1 = Mythread(1,"Thread1",5,1)
thread2 = Mythread(2,"Thread2",5,2)
thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)
for t in threads:
t.join()
'''
thread1 = Mythread(1,"Thread1",5,1)
thread2 = Mythread(2,"Thread2",5,2)
lock = threading.Lock()
with lock:
thread1.start()
thread2.start()
print("Exiting main thread ")
产生以下输出:
StartingThread1
StartingThread2
Exiting main thread
Thread1 : Sat May 04 02:21:54 2013_5
Thread1 : Sat May 04 02:21:55 2013_4
Thread2 : Sat May 04 02:21:55 2013_5
Thread1 : Sat May 04 02:21:56 2013_3
Thread1 : Sat May 04 02:21:57 2013_2
Thread2 : Sat May 04 02:21:57 2013_4
Thread1 : Sat May 04 02:21:58 2013_1
Duration for func print_time_Thread1 :5
ExitingThread1
Thread2 : Sat May 04 02:21:59 2013_3
Thread2 : Sat May 04 02:22:01 2013_2
Thread2 : Sat May 04 02:22:03 2013_1
Duration for func print_time_Thread2 :10
ExitingThread2
请帮助我理解为什么使用with语句时锁定不起作用,或者我完全误解了这个概念。即使定义了锁,我也不明白为什么会直接进入print("Exiting main thread")。
join
,也没有将它们设置为daemon=True
。这是非法的。在某些情况下它可以工作(但在不同的平台上会有不同的结果!),但您永远不应该依赖它。 - abarnertLock
甚至不是与Thread
相同类型的对象。这就像说“我写map(print, [1,2,3])
而不是2+4
,因为前者看起来更干净”。 - abarnert