我正在尝试对类似的输入字符串进行锁定。但锁不起作用。同一字符串的第二个锁不会等待,但第一次释放会破坏该锁,因此第二次释放会引发错误。
测试.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
最佳答案
在此应用程序中使用 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()
您提到希望对相同的字符串使用相同的锁,但在这种情况下,当然当一个字符串的锁结束时,使用同一字符串的其他线程的锁也会结束。也许如果你更多地解释你的动机,我可以建议另一个解决方案。
预计到达时间:如果您确定对于您的特定应用程序,您希望对同一字符串使用相同的锁,那么这将是一种方法:
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 的类)。
关于python - eval 锁不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8799221/