python线程锁未锁定其余线程

问题描述 投票:0回答:1

这是我的代码:

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_funcouter_func使用它来证明threading.Lock()是否可以传递给子功能。运行后,在我看来,该锁似乎不会锁定其他线程,因为打印消息会在锁的消息之间显示其他消息。

(锁的消息应为:......获得,.......处理........ release)

问题:

  1. 为什么锁不起作用,尤其是在线程开始工作时。

  2. 其他问题,我的打印消息有时不是从换行符开始的,如何解决?

python multithreading
1个回答
0
投票

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

确实。

© www.soinside.com 2019 - 2024. All rights reserved.