Python Rlock实现线程同步
import threading mylock = threading.RLock(); num = 0 class myThread(threading.Thread): def __init__(self, name): threading.Thread.__init__(self,name=name) def run(self): global num while True: mylock.acquire() print('%s locked, Number: %d' % (threading.current_thread().name, num)) if num >= 4: mylock.release() print('%s released, Number: %d' % (threading.current_thread().name, num)) break num += 1 print('%s released, Number: %d' % (threading.current_thread().name, num)) mylock.release() if __name__ == '__main__': thread1 = myThread('Thread_1') thread2 = myThread('Thread_2') thread1.start() thread2.start()
如果多个线程共同对某个数据修改,则可能岀现不可预料的结果,为了保的正确
性,需要对多个线程进行同步。使用 Thread对象的Lock和RLock可以实现简单的线程同步。.
这两个对象都有acquire方法和relate方法,对于那些每次只允许一个线程操作的数据,可
以将其操作放到acquire和release方法之间。