Python3——多线程之threading模块
目录
Python 提供了多个模块来支持多线程编程,包括 thread、 threading 和 Queue 模块等。程序是可以使用 thread 和 threading 模块来创建与管理线程。 thread 模块提供了基本的线程和锁定支持;而 threading 模块提供了更高级别、功能更全面的线程管理。使用 Queue 模块,用户可以创建一个队列数据结构,用于在多线程之间进行共享。(推荐使用threading模块比thread模块更高级)
-
Threading模块的对象
对象 | 描述 |
Thread | 线程对象 |
Lock | 互斥锁 |
Condition | 条件变量 |
Event | 事件,该事件发生后所有等待该事件的线程将激活 |
Semaphore | 信号量(计数器) |
Timer | 定时器,运行前会等待一段时间 |
Barrier | 创建一个障碍,必须达到指定数量线程才开始运行 |
-
Threading模块的Thread类
对象 | 描述 |
name | 线程名(属性) |
ident | 线程标识符(属性) |
daemon | 线程是否是守护线程(属性) |
_init_(group=None, tatget=None, name=None, args=(),kwargs ={}, verbose=None, daemon=None) | 实例化一个线程对象,需要有一个可调用的 target,以及其参数 args或 kwargs。还可以传递 name 或 group 参数,不过后者还未实现。此外, verbose 标 志 也 是 可 接 受 的。 而 daemon 的 值 将 会 设定thread.daemon 属性/标志 |
start() | 开启线程 |
run() | 定义线程功能的方法(通常在子类中被应用开发者重写) |
Barrier | 创建一个障碍,必须达到指定数量线程才开始运行 |
import threading
from time import ctime, sleep
loops = (3, 2)
class Mythread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args
''' rewrite run() '''
def run(self):
self.func(*self.args)
''' thread handle func --- while(1) '''
def loop(nloop, nsec):
while True:
print('start loop ' + str(nloop), 'at: ' + str(ctime()))
sleep(nsec)
def main():
threads = []
nloops = range(len(loops))
for i in nloops:
t = Mythread(loop, (i + 1, loops[i]), loop.__name__)
threads.append(t)
for i in nloops:
threads[i].start()
if __name__ == '__main__':
main()
-
queue模块(线程间通信)
Queue(maxsize = 0) | 创建一个先入先出队列。如果给定最大值,则在队列没有空间时阻塞;否则(没有指定最大值),为无限队列 |
LifoQueue(maxsize=0) | 创建一个后入先出队列。如果给定最大值,则在队列没有空间时阻塞;否则(没有指定最大值),为无限队列 |
PriorityQueue(maxsize=0) | 创建一个优先级队列。如果给定最大值,则在队列没有空间时阻塞,否则(没有指定最大值),为无限队列 |
Empty | 当对空队列调用 get*()方法时抛出异常 |
Full | 当对已满的队列调用 put*()方法时抛出异常 |
qsize () | 返回队列大小 |
empty() | 如果队列为空,则返回 True;否则,返回 False |
full() | 如果队列已满,则返回 True;否则,返回 False |
put (item, block=Ture, timeout=None) | 将 item 放入队列。如果 block 为 True(默认)且 timeout 为 None,则在有可用空间之前阻塞;如果 timeout 为正值,则最多阻塞 timeout 秒;如果 block 为 False,则抛出 Empty 异常 |
get (block=True, timeout=None) | 从队列中取得元素。如果给定了 block(非 0),则一直阻塞到有可用的元素为止 |
join() | 在队列中所有元素执行完毕并调用上面的 task_done()信号之前,保持阻塞 |
import threading
from random import randint
from queue import *
from time import ctime, sleep
class Mythread(threading.Thread):
def __init__(self, func, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
''' rewrite run() '''
def run(self):
self.func()
class MyQueue():
def __init__(self, q, loops):
self.q = q
self.loops = loops
def WriteQueue(self):
self.q.put('xxx', 1)
def ReadQueue(self):
value = self.q.get(1)
print('value: ' + str(value))
return value
def Writer(self):
while 1:
for i in range(self.loops):
self.WriteQueue()
def Reader(self):
while 1:
for i in range(self.loops):
aaa = self.ReadQueue()
print("aaa = " + str(aaa))
def main():
que = Queue(32)
nloops = randint(2, 5)
q = MyQueue(que, nloops)
t1 = Mythread(q.Writer, q.Writer.__name__)
t2 = Mythread(q.Reader, q.Reader.__name__)
t1.start()
t2.start()
if __name__ == '__main__':
main()