1
我試圖鎖定類似的輸入字符串。但鎖不起作用。同一個字符串的第二個鎖不會等待,但第一個版本會銷燬該鎖,因此第二個版本會引發錯誤。eval鎖不起作用
test.py
import threading
import time
class TestThread(threading.Thread):
def __init__(self, input):
threading.Thread.__init__(self)
self.input = input
lock_wrap = "TestThread." + self.input + " = threading.Lock()"
eval(compile(lock_wrap,'<string>','exec'))
def run(self):
acquire_wrap = "TestThread." + self.input + ".acquire()"
exec(compile(acquire_wrap,'<string>','exec'))
print("waste some time for %s" % self.input)
time.sleep(30)
print("%s done" % self.input)
release_wrap = "TestThread." + self.input + ".release()"
exec(compile(release_wrap,'<string>','exec'))
my_threads = []
while True:
input = raw_input("> ")
if input == "end":
break
thread = TestThread(input)
my_threads.append(thread)
thread.start()
for t in my_threads:
t.join()
結果
$ python test.py
> foo
> waste some time for foo
bar
waste some time for bar
> foo
> waste some time for foo
foo done
bar done
foo done
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
self.run()
File "test.py", line 19, in run
exec(compile(release_wrap,'<string>','exec'))
File "<string>", line 1, in <module>
error: release unlocked lock
這正是我正在尋找的。現在我只需要了解它是如何工作的,哈哈。非常感謝大衛! – Germar 2012-01-10 21:55:03
我很高興能幫到你!再次,確保您在使用此操作之前確實想要爲多個線程使用相同的鎖。 – 2012-01-10 23:05:41