我正在尝试对类似的输入字符串进行锁定。但是锁不起作用。同一个字符串的第二个锁不等待,但第一个版本将破坏锁定,因此第二个版本将引发错误。
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
答案 0 :(得分:3)
对此应用程序使用eval没有意义;为什么不为每个线程保留一个锁?
class TestThread(threading.Thread):
def __init__(self, input):
threading.Thread.__init__(self)
self.input = input
self.lock = threading.Lock()
def run(self):
self.lock.acquire()
print("waste some time for %s" % self.input)
time.sleep(5)
print("%s done" % self.input)
self.lock.release()
你提到想要对相同的字符串使用相同的锁,但在这种情况下,当然当一个字符串的锁定结束时,其他线程的锁定也会使用相同的字符串。也许如果你更多地解释了你的动机,我可以建议另一个解决方案。
ETA:如果您确定,对于您的特定应用程序,您希望对同一个字符串具有相同的锁定,这将是一种方法:
LOCK_DICT = {}
LOCK_DICT_LOCK = threading.RLock()
class TestThread(threading.Thread):
def __init__(self, input):
threading.Thread.__init__(self)
self.input = input
with LOCK_DICT_LOCK:
if self.input not in LOCK_DICT:
LOCK_DICT[self.input] = threading.Lock()
def run(self):
with LOCK_DICT_LOCK:
lock = LOCK_DICT[self.input]
lock.acquire()
print("waste some time for %s" % self.input)
time.sleep(5)
print("%s done" % self.input)
lock.release()
请注意,此特定版本使用全局变量,这不是理想的设计,但它比使用上面的设计中的eval
更好 (这也保留了变量类属性)。无论你使用什么代码,当然可以将LOCK_DICT和LOCK_DICT_LOCK置于非全局的地方(例如,你调用ThreadManager的类)。