我是一個嘗試瞭解線程模塊的Python的noob。 我使用的動機蟒蛇2.7.One在蟒蛇with_statement被給了是隨着聲明和python線程
with threading.Lock():
//User defined function in a new thread
我不知道如果我理解正確的話代碼的模式,但我最初的設想是這樣的代碼應該AQUIRE鎖在子線程完成後釋放的mainthread上。 然而,這個腳本
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_statement或有我徹底誤解了concept.I很困惑,爲什麼我得到直接打印(「退出主線程」),甚至通過定義鎖定
創建一個你不與任何其他線程共享的鎖通常沒有意義。你希望鎖能保護你不受這些傷害? – abarnert 2013-05-04 00:38:11
我所試圖做的,是繼續這種說法 \t打印( 「退出主線程」) 在此之後: \t與鎖: \t \t thread1.start() \t \t thread2.start() 現在這作品時,我明確地調用 \t \t thread1.join() \t \t thread2.join() 但我會更喜歡使用with_statement,因爲它看起來更乾淨。 – Rahuketu86 2013-05-04 00:39:17
附註:您不是在線程上調用'join',也不是將它們設置爲'daemon = True'。這是非法的。它會在某些情況下工作(但是在不同平臺上有不同的情況!),但是你不應該依賴它。 – abarnert 2013-05-04 00:42:58