python线程锁不会锁定线程的其余部分

2024-04-19 01:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

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()

我试图创建inner_func,它被outer_func用来证明threading.Lock()是否可以传递给子函数。 在运行之后,锁似乎并没有锁定其他线程,因为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)

如上所述,线程6已经获得了锁,但是在线程6中释放锁之前,线程7仍然处于活动状态

是不是说锁坏了?如果没有,如何证明锁何时处于活动状态?或者在锁定单个线程的活动期间,其他线程不活动

以下是另一个打印问题:

Thread-6 - outsider_function - input: dThread-1 - inner_function - lock - acquire

上面应该打印在两个不同的行。如何修复?谢谢


Tags: selflockinputdeffunctioncurrentitemthread
1条回答
网友
1楼 · 发布于 2024-04-19 01:16:00

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}')

是的

相关问题 更多 >