0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

Python3多线程核心知识

马哥Linux运维 来源:未知 作者:李倩 2018-04-16 11:46 次阅读
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。

每个线程都有他自己的一组CPU寄存器,称为线程的上下文,该上下文反映了线程上次运行该线程的CPU寄存器的状态。

指令指针和堆栈指针寄存器是线程上下文中两个最重要的寄存器,线程总是在进程得到上下文中运行的,这些地址都用于标志拥有线程的进程地址空间中的内存。

线程可以被抢占(中断)。

在其他线程正在运行时,线程可以暂时搁置(也称为睡眠) -- 这就是线程的退让。

线程可以分为:

内核线程:由操作系统内核创建和撤销。

用户线程:不需要内核支持而在用户程序中实现的线程。

Python3 线程中常用的两个模块为:

_thread

threading(推荐使用)

函数式

调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下:

_thread.start_new_thread ( function, args[, kwargs] )

参数说明:

function - 线程函数。

args - 传递给线程函数的参数,他必须是个tuple类型。

kwargs - 可选参数。

import _thread, time# 定义线程函数def print_time(threadName, delay):

count = 0 while count < 5:    

time.sleep(delay)

count += 1

# 返回当前时间的时间戳(1970纪元后经过的浮点秒数), 并格式化输出

print("{}: {}".format(threadName, time.ctime(time.time()) ))try:

_thread.start_new_thread( print_time, ("Thread-1", 2))

_thread.start_new_thread( print_time, ("Thread-2", 4))except:

print("Error")while 1: # 让线程有足够的时间完成 pass

E:\PyPro>python thread.pyThread-1: Thu Apr 12 09:01:56 2018Thread-2: Thu Apr 12 09:01:58 2018Thread-1: Thu Apr 12 09:01:58 2018Thread-1: Thu Apr 12 09:02:00 2018Thread-2: Thu Apr 12 09:02:02 2018Thread-1: Thu Apr 12 09:02:02 2018Thread-1: Thu Apr 12 09:02:05 2018Thread-2: Thu Apr 12 09:02:06 2018Thread-2: Thu Apr 12 09:02:10 2018Thread-2: Thu Apr 12 09:02:14 2018

类封装式

threading 模块除了包含 _thread 模块中的所有方法外,还提供的其他方法:

threading.currentThread(): 返回当前的线程变量。

threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。

threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:

run():用以表示线程活动的方法。

start():启动线程活动。

join([time]):等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。

isAlive():返回线程是否活动的。

getName():返回线程名。

setName():设置线程名。

import threading, time# 创建进程类class myThread(threading.Thread):

# 构造函数 def __init__(self, threadID, name, counter):

threading.Thread.__init__(self)

self.threadID = threadID

self.name = name

self.counter = counter

# 重写run()

def run(self):

print("Thread Strat:" + self.name)

print_time(self.name, self.counter, 5)

print("Thread Exit:" + self.name)

def print_time(threadName, delay, counter):

while counter:

time.sleep(delay)

print("{}: {}".format(threadName, time.ctime(time.time()) ))

counter -= 1

# 创建线程thread1 = myThread(1001, "Thread-1", 1)thread2 = myThread(1002, "Thread-2", 2)# 开启线程print("Thread-1 is Alive? ", thread1.isAlive())thread1.start()thread2.start()print("Thread-1 is Alive? ", thread1.isAlive())thread1.join()thread2.join()print("Thread-1 is Alive? ", thread1.isAlive())print("exit")

E:\PyPro>python threadClass.pyThread-1 is Alive? FalseThread Strat:

Thread-1Thread Strat:

Thread-2Thread-1 is Alive? TrueThread-1: Thu Apr 12 10:15:53 2018Thread-1:

Thu Apr 12 10:15:54 2018Thread-2: Thu Apr 12 10:15:54 2018Thread-1: Thu Apr 12 10:15:55 2018Thread-1:

Thu Apr 12 10:15:56 2018Thread-2: Thu Apr 12 10:15:56 2018Thread-1: Thu Apr 12 10:15:57 2018Thread Exit:

Thread-1Thread-2: Thu Apr 12 10:15:58 2018Thread-2: Thu Apr 12 10:16:00 2018Thread-2: Thu Apr 12 10:16:02 2018Thread Exit:

Thread-2Thread-1 is Alive? Falseexit

不难发现,线程是通过start()函数激活,而不是对象建立时激活的!

线程同步

多线程的优势在于可以同时运行多个任务(至少感觉起来是这样)。但是当线程需要共享数据时,可能存在数据不同步的问题。

使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire 和 release 方法之间。

import threading, time# 创建锁threadLock = threading.Lock()# 创建线程列表threads = []class myThread(threading.Thread):

def __init__(self, threadID, name, counter):

threading.Thread.__init__(self)

self.threadID = threadID

self.name = name

self.counter = counter

def run(self):

print("Thread Start: " + self.name)

# 获取锁,同步线程

threadLock.acquire()

print_time(self.name, self.counter, 3)

# 释放锁,开启下一个线程

threadLock.release()

print("Thread Exit: " + self.name)

def print_time(threadName, delay, counter):

while counter:

time.sleep(delay)

print("{}: {}".format(threadName, time.ctime()))

counter -= 1

# 创建线程thread1 = myThread(1001, "Thread-1", 1)thread2 = myThread(1002, "Thread-2", 2)# 开启线程thread1.start()thread2.start()# 添加线程列表threads.append(thread1)threads.append(thread2)# 等待所有线程完成for t in threads: t.join()print("exit")

E:\PyPro>python synchronize.pyThread Start: Thread-1Thread Start: Thread-2Thread-1: Thu Apr 12 11:00:49 2018Thread-1: Thu Apr 12 11:00:50 2018Thread-1: Thu Apr 12 11:00:51 2018Thread Exit: Thread-1Thread-2: Thu Apr 12 11:00:53 2018Thread-2: Thu Apr 12 11:00:55 2018Thread-2: Thu Apr 12 11:00:57 2018Thread Exit: Thread-2exit

线程优先级队列

Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO队列Queue,LIFO队列LifoQueue,和优先级队列 PriorityQueue。

这些队列都实现了锁原语,能够在多线程中直接使用,可以使用队列来实现线程间的同步。

Queue 模块中的常用方法:

Queue.qsize() 返回队列的大小

Queue.empty() 如果队列为空,返回True,反之False

Queue.full() 如果队列满了,返回True,反之False

Queue.full 与 maxsize 大小对应

Queue.get([block[, timeout]])获取队列,timeout等待时间

Queue.get_nowait() 相当Queue.get(False)

Queue.put(item) 写入队列,timeout等待时间

Queue.put_nowait(item) 相当Queue.put(item, False)

Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号

Queue.join() 实际上意味着等到队列为空,再执行别的操作

import queue, threading, timeexitFlag = 0# 创建锁queueLock = threading.Lock()# 创建队列workQueue = queue.Queue(10)class myThread(threading.Thread):

def __init__(self, threadID, name, q):

threading.Thread.__init__(self)

self.threadID = threadID

self.name = name

self.q = q

def run(self):

print("Thread Start: " + self.name)

process_data(self.name, self.q)

print("Thread Exit: " + self.name)

def process_data(threadName, q):

while not exitFlag:

queueLock.acquire()

if not workQueue.empty():

data = q.get()

queueLock.release()

print("{} processing {}".format(threadName, data))

else:

queueLock.release()

time.sleep(1)threadList = ["Thread-1", "Thread-2", "Thread-3"]nameList = ["One", "Two", "Three", "Four", "Five"]threads = []threadID = 1# 创建新线程for tName in threadList:

thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread)

threadID += 1# 填充队列queueLock.acquire()print

("队列填充中>>>>>>>>>>>>>>")time.sleep(1)for word in nameList: workQueue.put(word)print("队列填充完毕>>>>>>>>>>>>>>")queueLock.release()# 等待队列清空while not workQueue.empty(): pass# 通知线程退出exitFlag = 1# 等待所有线程完成for t in threads: t.join()print("exit")

E:\PyPro>python queueue.pyThread Start: Thread-1Thread Start: Thread-2Thread Start: Thread-3队列填充中>>>>>>>>>>>>>>队列填充完毕>>>>>>>>>>>>>>Thread-3 processing OneThread-1 processing TwoThread-2 processing ThreeThread-3 processing FourThread-1 processing FiveThread Exit: Thread-2Thread Exit: Thread-1Thread Exit: Thread-3exit

源码中其实实现了三个进程读取同一个队列,按照先进先出原则实现锁定。

用start方法来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码。通过调用Thread类的start()方法来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到cpu时间片,就开始执行run()方法,这里方法 run()称为线程体,它包含了要执行的这个线程的内容,Run方法运行结束,此线程随即终止。

join的作用是保证当前线程执行完成后,再执行其它线程。join可以有timeout参数,表示阻塞其它线程timeout秒后,不再阻塞。。一般线程的start()之后,所有操作结束后都要进行thread.join()。确保语句的输出是join()后面的程序是等线程结束后再执行的。

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 寄存器
    +关注

    关注

    31

    文章

    5625

    浏览量

    130705
  • cpu
    cpu
    +关注

    关注

    68

    文章

    11378

    浏览量

    226480
  • 线程
    +关注

    关注

    0

    文章

    511

    浏览量

    20892

原文标题:十分钟带你了解 Python3 多线程核心知识

文章出处:【微信号:magedu-Linux,微信公众号:马哥Linux运维】欢迎添加关注!文章转载请注明出处。

收藏 人收藏
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

    评论

    相关推荐
    热点推荐

    AI算法核心知识清单(深度实战版3

    四、深度学习核心知识(进阶必备)1.模型训练关键技术(深度学习实战核心)损失函数(模型优化目标)分类任务损失函数(续):稀疏多分类交叉熵损失
    的头像 发表于 04-29 17:18 739次阅读
    AI算法<b class='flag-5'>核心知识</b>清单(深度实战版<b class='flag-5'>3</b>)

    AI 算法核心知识清单(深度实战版2)

    三、机器学习核心算法(入门到实战)​1.监督学习算法(已知标签的模型训练)​线性模型​线性回归(回归任务):​核心原理:假设y=w₀+w₁x₁+w₂x₂+...+wₙxₙ+ε(ε为误差项),通过
    的头像 发表于 04-24 11:58 280次阅读
    AI 算法<b class='flag-5'>核心知识</b>清单(深度实战版2)

    AI 算法核心知识清单(深度实战版1)

    ​一、基础数学功底(算法的底层基石)​1.线性代数(AI数据处理与模型计算核心)​核心概念深度解析​向量:n维有序数组,是AI中数据的基本表示形式(如图像像素、文本特征、用户行为数据),支持加法、数
    的头像 发表于 04-24 11:16 219次阅读
    AI 算法<b class='flag-5'>核心知识</b>清单(深度实战版1)

    Java并发编程的“基石”——多线程概念初识

    之下,隐藏着一个庞大而复杂的“算力帝国”。如何将成千上万块 GPU 的算力精准、高效地分配给无数个并发的 AI 任务?这便是 AI 算力调度的核心使命。在这个看似属于 Python 和 C++ 的绝对
    发表于 04-16 18:50

    安装 Python VisionFive_GPIO失败是哪里出了问题?

    尽管按照最新的文档,我在安装 VisionFive.gpio 包时仍然收到错误 sudo apt 安装 libxml2-dev libxslt-dev python3 -m pip 安装请求
    发表于 02-11 06:13

    【瑞萨RA × Zephyr评测】多线程和看门狗

    本文章旨在评估使用 Zephyr RTOS 在 Renesas FPB-RA6E2 开发板上实现多线程调度与硬件看门狗功能的应用。评估内容包括任务调度、看门狗初始化流程、主程序逻辑的详细解析,以及实验现象与数据分析。
    的头像 发表于 01-10 10:23 2783次阅读
    【瑞萨RA × Zephyr评测】<b class='flag-5'>多线程</b>和看门狗

    解析Linux的进程、线程和协程

    和系统资源。线程的引入使得多核处理器得以充分利用,因为多线程程序可以更有效地分配和管理多核心的计算资源。 线程的特点包括: (1)共享性:线程
    发表于 12-22 11:00

    多线程的系统

    ) { /* 无限循环,不能返回 */ for (;;) { /* 线程实体 */ if (flag3) { } } } 相比前后台系统中后台顺序执行的程序主体,在多线程系统中,根据程序的功能
    发表于 12-08 07:55

    Linux多线程对比单线程的优势

    :「资源利用率」:通过多线程,可以更有效地利用CPU资源,特别是多核CPU。「并行处理」:线程允许同时执行多个任务,提高程序的执行效率。「简化设计」:使用线程可以简化程序设计,因为线程
    发表于 12-01 06:11

    【CIE全国RISC-V创新应用大赛】MUSE PI PRO 測評

    if=/dev/zero of=/mnt/usb/test.bin bs=1M count=10 Python环境:python3 --version(3.10刚好支持YOLO)→pip3
    发表于 11-28 19:00

    rt-thread studio 如何进行多线程编译?

    ,使用的是5800h+32g内存+sn550 ssd,开启16线程编译时cpu的占用率也只能到30%,编译完整个工程需要3分钟 感觉多线程编译设置没有生效,有办法提高编译速度吗 rtthread studio版本是 2.2.9
    发表于 10-11 09:16

    【HZ-T536开发板免费体验】—— linux创建线程

    自己的私有资源。 在linux系统中,线程状态通常反映了当前线程的当前活动和执行阶段。 主要分为: 1。运行转态 2。阻塞转态 3。终止状态 如何区分单线程
    发表于 09-01 21:31

    多线程的安全注意事项

    多线程安全是指多个线程同时访问或修改共享资源时,能够保证程序的正确性和可靠性。 开发者选择TaskPool或Worker进行多线程开发时,在TaskPool和Worker的工作线程中导
    发表于 06-20 07:49

    Hi3861 wifiiot_hispark_pegasus 按教程安装python3 -m pip install build/lite 报错

    问题1: 报错: 问题2: 我安装网上搜的方法执行 python3 -m pip install --user ohos-build==0.4.3 hb -v [OHOS INFO] hb
    发表于 06-14 16:48

    工控一体机多线程任务调度优化:聚徽分享破解工业复杂流程高效协同密码

    在当今工业 4.0 的浪潮下,工业生产正朝着高度自动化、智能化的方向大步迈进。生产流程日益复杂,众多任务需要同时、高效地协同执行,这对工业控制系统的核心 —— 工控一体机提出了前所未有的挑战。多线程
    的头像 发表于 05-28 14:06 789次阅读