下面是我的代码:
def inner_func(lock):
with lock:
print (f'{threading.current_thread().getName()} - inner_function - lock - acquire')
print (f'{threading.current_thread().getName()} - inner_function - lock - processing')
print (f'{threading.current_thread().getName()} - inner_function - lock - release')
print(f'{threading.current_thread().getName()} - inner_function')
def outer_func(a, lock):
inner_func(lock)
print(f'{threading.current_thread().getName()} - outsider_function - input: {a}')
class Worker():
def __init__(self, num_threads, input_item):
self.t = threading
self.lock = self.t.Lock()
self.q = queue.Queue()
self.num_thread = num_threads
self.input_item = input_item
def worker(self):
while True:
item = self.q.get()
if item: item.append(self.lock)
if not item:
break
outer_func(*item)
self.q.task_done()
def main(self):
threads = []
for _ in range(self.num_thread):
t = self.t.Thread(target=self.worker)
t.start()
threads.append(t)
for item in self.input_item:
self.q.put(item)
self.q.join()
for _ in range(self.num_thread):
self.q.put(None)
for t in threads:
t.join()
container = [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g']]
Worker(7, container).main()我正在尝试创建outer_func用来验证threading.Lock()是否可以传递给子函数的inner_func。运行之后,看起来锁并没有锁定其他线程,因为print消息在锁的消息之间显示了其他消息。
打印结果如下:
.......(other print)
Thread-6 - inner_function - lock - acquire
Thread-7 - outsider_function - input: c
Thread-6 - inner_function - lock - processing
Thread-6 - inner_function - lock - release
.......(other print)如上所述,Thread-6已经获得了锁,但在Thread-6中的锁释放之前,Thread-7仍然处于活动状态。
这是否意味着锁不起作用了?如果不是,我如何证明锁何时处于活动状态?或者当在单线程中的锁的激活期间其它线程不活动时。
下面是关于打印的另一个问题:
Thread-6 - outsider_function - input: dThread-1 - inner_function - lock - acquire上面应该打印在两个不同的行中。如何修复它?谢谢。
发布于 2019-12-07 11:49:04
with lock:块外部的印记相对于锁是无序的。如果你想订购它们,你需要将它们包装在它们自己的with lock:中。
考虑一下:
def inner_func(lock):
with lock:
print (f'{threading.current_thread().getName()} - inner_function - lock - acquire')
print (f'{threading.current_thread().getName()} - inner_function - lock - processing')
print (f'{threading.current_thread().getName()} - inner_function - lock - release')
with lock:
print(f'{threading.current_thread().getName()} - inner_function')
def outer_func(a, lock):
inner_func(lock)
with lock:
print(f'{threading.current_thread().getName()} - outsider_function - input: {a}')确实如此。
https://stackoverflow.com/questions/59222692
复制相似问题