首页 > 编程 > Python > 正文

Python线程同步的实现代码

2020-02-15 23:05:46
字体:
来源:转载
供稿:网友

本文介绍Python中的线程同步对象,主要涉及 thread 和 threading 模块。

threading 模块提供的线程同步原语包括:Lock、RLock、Condition、Event、Semaphore等对象。

线程执行

join与setDaemon

子线程在主线程运行结束后,会继续执行完,如果给子线程设置为守护线程(setDaemon=True),主线程运行结束子线程即结束;

如果join()线程,那么主线程会等待子线程执行完再执行。

import threadingimport timedef get_thread_a(): print("get thread A started") time.sleep(3) print("get thread A end")def get_thread_b(): print("get thread B started") time.sleep(5) print("get thread B end")if __name__ == "__main__": 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()  end_time = time.time() print("execution time: {}".format(end_time - start_time))

thread_a是join,首先子线程thread_a执行,thread_b是守护线程,当主线程执行完后,thread_b不会再执行执行结果如下:

get thread A started
get thread B started
get thread A end
execution time: 3.003199815750122

线程同步

当线程间共享全局变量,多个线程对该变量执行不同的操作时,该变量最终的结果可能是不确定的(每次线程执行后的结果不同),如:对count变量执行加减操作 ,count的值是不确定的,要想count的值是一个确定的需对线程执行的代码段加锁。

python对线程加锁主要有Lock和Rlock模块

Lock: 

from threading import Locklock = Lock()lock.acquire()lock.release() 

Lock有acquire()和release()方法,这两个方法必须是成对出现的,acquire()后面必须release()后才能再acquire(),否则会造成死锁

Rlock:

鉴于Lock可能会造成死锁的情况,RLock(可重入锁)对Lock进行了改进,RLock可以在同一个线程里面连续调用多次acquire(),但必须再执行相同次数的release()

from threading import RLocklock = RLock()lock.acquire()lock.acquire()lock.release()lock.release() 

condition(条件变量),线程在执行时,当满足了特定的条件后,才可以访问相关的数据

import threadingdef get_thread_a(condition): with condition:  condition.wait()  print("A : Hello B,that's ok")  condition.notify()  condition.wait()  print("A : I'm fine,and you?")  condition.notify()  condition.wait()  print("A : Nice to meet you")  condition.notify()  condition.wait()  print("A : That's all for today")  condition.notify()def get_thread_b(condition): with condition:  print("B : Hi A, Let's start the conversation")  condition.notify()  condition.wait()  print("B : How are you")  condition.notify()  condition.wait()  print("B : I'm fine too")  condition.notify()  condition.wait()  print("B : Nice to meet you,too")  condition.notify()  condition.wait()  print("B : Oh,goodbye")if __name__ == "__main__": condition = threading.Condition() thread_a = threading.Thread(target=get_thread_a, args=(condition,)) thread_b = threading.Thread(target=get_thread_b, args=(condition,)) thread_a.start() thread_b.start()             
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表