Python使多线程中的每个锁都成为可能

时间:2018-03-02 20:40:12

标签: python multithreading locking

我正在考虑如何为每个线程制作几个锁。

我现在有3个帖子。

A:主线程(数据发送) B:数据接收线程 C:每2秒线程发送一次数据

除了发送时间之外,我不想停止B(接收线程)。 如何在A,B之间以及A,C之间轻松使用锁定!! ...

class A:
    def __init__():
        self._A_B_lock = RLock()
        self._A_C_lock = RLock()
        self._B = threading.Thread(target=B_receiving_thread, args=(self._A_B_lock,) ... ).start()
        self._C = threading.Thread(target=C_sending_2sec_thread, args=(self._A_C_lock,) ... ).start()

    def sending():
        with A_B_lock:
            sending_data()

    def B_receiving_thread(self,A_B_lock):
        while(1):
            with A_B_lock:
                receiving_data()
            #do something

    def C_sending_2sec_thread(self,A_C_lock):
        while(1):
            with A_C_lock:
                self.sending()

    # actually I want to make decorator with A_C_lock, I have so many functions.
    def so_many_functions():
        with self.A_C_lock:
            #do important thing

此代码不起作用..

1 个答案:

答案 0 :(得分:0)

装饰师是个好主意。你可以用这个

def decorator(*locks):
    def _decorator(func):
        def inner_function(*args, **kwargs):
            for lock in locks:
                lock.acquire()
            value = func(*args, **kwargs)
            for lock in locks:
                lock.release()
            return value
        return inner_function
    return _decorator

然后你装饰每个函数,并作为参数传递该函数在不干扰其他人的情况下完成工作所需的所有锁。像这样,

lock1 = threading.Lock()
lock2 = threading.Lock()

@decorator(lock1, lock2)
def f1(word):
    for char in word:
        print(char)
    '''DO STUFF'''


@decorator(lock1, lock2)
def f2(word):
    for char in word:
        print(char)
    '''
    DO STUFF
    '''


t1 = threading.Thread(target=f1, args=('Hello ',))
t2 = threading.Thread(target=f2, args=('world',))
t1.start()
t2.start()

这只是一个虚拟示例,但您可以轻松地将其应用于您的代码。关于它的好处是,你可以轻松地选择你想要用于每个不同功能的锁。

希望有所帮助