rainit2006 / Python-room

my python room
0 stars 0 forks source link

Python的线程 #22

Open rainit2006 opened 5 years ago

rainit2006 commented 5 years ago

rainit2006 commented 5 years ago

参考: https://www.w3xue.com/exp/article/201810/2199.html https://qiita.com/__init__/items/74b36eba31ccbc0364ed

rainit2006 commented 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会强行结束。

rainit2006 commented 5 years ago

■线程同步 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有是三个特点:

  1. 谁拿到谁释放。如果线程A拿到锁,线程B无法释放这个锁,只有A可以释放;
  2. 同一线程可以多次拿到该锁,即可以acquire多次;
  3. acquire多少次就必须release多少次,只有最后一次release才能改变RLock的状态为unlocked)
rainit2006 commented 5 years ago

■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()