# 线程间同步

#Lock​-互斥锁

最低级的同步指令。

import threading

class SharedCounter:
    '''
    A counter object that can be shared by multiple threads.
    '''
    def __init__(self, initial_value = 0):
        self._value = initial_value
        self._value_lock = threading.Lock()

    def incr(self,delta=1):
        '''
        Increment the counter with locking
        '''
        with self._value_lock:
             self._value += delta

    def decr(self,delta=1):
        '''
        Decrement the counter with locking
        '''
        with self._value_lock:
             self._value -= delta

#RLock​-可重入锁

一个线程可多次获取,最后释放即可。

import threading

class MyClass:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.lock = threading.RLock()

    def update(self, thread_name):
        print("Waiting: ", thread_name)
        self.lock.acquire()
        try:
            print("Acquired: ", thread_name)
            self.a += 1
            self.b += 1
            print("a =", self.a, "b =", self.b)
        finally:
            self.lock.release()
            print("Released: ", thread_name)

if __name__ == "__main__":
    c = MyClass()
    t1 = threading.Thread(target=c.update, args=("Thread-1",))
    t2 = threading.Thread(target=c.update, args=("Thread-2",))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
"""
Waiting:  Thread-1
Acquired:  Thread-1
Waiting:  Thread-2
a = 2 b = 3
Released:  Thread-1
Acquired:  Thread-2
a = 3 b = 4
Released:  Thread-2
"""

# Condition​-条件对象

# Semaphore​-信号量对象

# Event​-事件对象

# Timer​-定时器对象

# Barrier​-栅栏对象