Open rainit2006 opened 5 years ago
■ join与setDaemon 子线程在主线程运行结束后,会继续执行到结束. 如果给子线程设置为守护线程(setDaemon=True),主线程运行结束子线程即结束; 如果join()线程,那么主线程会等待子线程执行完再执行。
例子:
thread_a = threading.Thread(target=get_thread_a)
thread_b = threading.Thread(target=get_thread_b)
start_time = time.time()
thread_b.setDaemon(True)
thread_a.start()
thread_b.start()
thread_a.join()
print("Done")
主线程会等thread_a结束后再执行print,然后退出。主线程退出时,thread_b会强行结束。
■线程同步 python对线程加锁主要有Lock和Rlock模块。 Lock有acquire()和release()方法,这两个方法必须是成对出现的,acquire()后不要忘记执行release()。
Rlock: 鉴于Lock可能会造成死锁的情况,RLock(可重入锁)对Lock进行了改进,RLock可以在同一个线程里面连续调用多次acquire(),但必须再执行相同次数的release()。 https://python-parallel-programmning-cookbook.readthedocs.io/zh_CN/latest/chapter2/07_Thread_synchronization_with_RLock.html (译者注:RLock原作解释的太模糊了,译者在此擅自添加一段。RLock其实叫做“Reentrant Lock”,就是可以重复进入的锁,也叫做“递归锁”。 这种锁对比Lock有是三个特点:
■Condition(条件变量) 线程在执行时,当满足了特定的条件后,才可以访问相关的数据。 https://python-parallel-programmning-cookbook.readthedocs.io/zh_CN/latest/chapter2/09_Thread_synchronization_with_a_condition.html
condition.wait() condition.notifyAll() //释放锁,所有调用wait()的线程可以往下执行了。 condition.notify() //释放锁,调用wait()的线程可以往下执行了。 condition.release()