[代码仓库]Python3多线程编程

首先导入模块

import threading
from queue import Queue

threading是线程模块,queue是系统提供的线程间通信队列,其中Queue为先进先出队列

thread1 = threading.Thread(target = target_function ,daemon = True)#target中是目标函数名,daemon为设置守护线程,true为守护线程,false为非守护。当父线程退出时,需要等待非守护线程结束,守护线程则跟随父线程退出
thread1.start()#通过start启动线程,如果一个线程结束了,不能通过start重启线程,需要重新声明。也就是说线程是一次性的。
communicatingQueue = Queue()#声明队列
communicatingQueue.put(something)#向队列中放值
var = communicatingQueue.get()#从队列中取出一个值,如果队列为空则阻塞

应用这些就足以应对一般的python多线程编程场景了

猜你喜欢

转载自www.cnblogs.com/trickofjoker/p/9325665.html