python_threading多线程、queue安全队列

简介: python_threading多线程、queue安全队列

多线程


image.png

image.png

threading库

常用方法

  • currentThread() 返回当前的线程变量
  • enumerate() 返回一个正在运行的线程list
  • activeCount() 返回正在运行的吸纳从数量(类似len(enumerate))

thread类

查询定义的thread类中start、run等方法

thread类

  • run() 线程活动的方法
  • start() 启动线程
  • join([time]) 阻塞调用线程直至线程的joiin()方法被调用终止
  • isActive 是否执行
  • getName() 但返回线程的名字
  • setName() 设置线程的名字

例:单线程、多线程分别执行两个函数的过程

import threading,time
def coding():
    for t in range(0,2):
        print('正在写python!')
        run_count()
        time.sleep(1)#延迟1s
def game():
    for t in range(0,2):
        print('游戏中!')
        run_count()
        time.sleep(1)#延迟1秒
def run_count():
    print('当前线程数量:',threading.active_count())
def single_thread():#单线程
    coding()
    game()
def muti_thread():#多线程
    fun1=threading.Thread(target=coding)
    fun2=threading.Thread(target=game)
    fun1.start()
    fun2.start()
if __name__=='__main__':
    print('单线程')
    single_thread()#
    print('多线程')
    muti_thread()

继承thread类

重构上面的代码

import threading,time
class codeWork(threading.Thread):#继承thread.Thread类
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name#名字自定义
    def run(self):
        the_thread=threading.current_thread()
        for i in range(2):
            print('正在写python!',the_thread.name)
            time.sleep(1)
class gameWork(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name#名字自定义
    def run(self):
        the_thread=threading.current_thread()
        for i in range(2):
            print('游戏中',the_thread.name)
            time.sleep(1)
def muti_thread():
    th1=codeWork('写代码的进程')
    th2=gameWork('游戏的进程')
    th1.start()
    th2.start()
if __name__=='__main__':
    muti_thread()

全局变量的问题

不加线程锁

因为多线程执行的不确定性,粗暴的更改全局变量可能会造成bug

例:多线程执行value++,查看全局变量value的值

import threading
value=0
class global_Work1(threading.Thread):#继承thread.Thread类
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name#名字自定义
    def run(self):
        the_thread=threading.current_thread()
        global value  # 定义全局变量
        for i in range(1,20):
            value+=1
            print('全局变量c:',value,'\t运行的进程:',threading.active_count(),the_thread.name)
class global_Work2(threading.Thread):#继承thread.Thread类
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name#名字自定义
    def run(self):
        the_thread=threading.current_thread()
        global value  # 定义全局变量
        for i in range(1,20):
            value+=1
            print('全局变量c:',value,'\t运行的进程:',threading.active_count(),the_thread.name)
def muti_thread():
    th1=global_Work1('全局变量测试1')
    th2 = global_Work1('全局变量测试2')
    th1.start()
    th2.start()
if __name__=='__main__':
    # global c  # 定义全局变量
    muti_thread()

添加线程锁Lock(线程同步)

threading.Lock()

  • acquire()
  • release()

queue线程安全队列

内置的线程安全模块queue(同步、安全,fifo)

  • qsize() 队列大小
  • empty() 队列是否为空
  • full() 队列是否满了
  • get()队列的最后一个数据
  • put() 数据加入队列

例:queue同步执行

import queue
import threading
import time
exitFlag = 0
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("开始 " + self.name)
        process_data(self.name, self.q)
        print("退出 " + self.name)
def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()#获取线程之后释放锁
            print("%s 运行 %s" % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)
if __name__=='__main__':
    threadList = ["Thread-1", "Thread-2", "Thread-3"]
    nameList = ["线程1", "线程2", "线程3", "线程4", "线程5"]  #
    queueLock = threading.Lock()  # 线程锁
    workQueue = queue.Queue(10)  # 大小为10的队列
    threads = []
    threadID = 1
    # 创建新线程
    for tName in threadList:  # 分配线程名字
        thread = myThread(threadID, tName, workQueue)
        thread.start()
        threads.append(thread)
        threadID += 1
    # 填充队列
    queueLock.acquire()  # 加锁
    for word in nameList:
        workQueue.put(word)
    queueLock.release()  # 解锁
    # 等待队列清空
    while not workQueue.empty():
        pass#占位
    # 通知线程是时候退出
    exitFlag = 1
    # 等待所有线程完成
    for t in threads:
        t.join()
    print("Exiting Main Thread")


目录
相关文章
|
4月前
|
人工智能 安全 调度
Python并发编程之线程同步详解
并发编程在Python中至关重要,线程同步确保多线程程序正确运行。本文详解线程同步机制,包括互斥锁、信号量、事件、条件变量和队列,探讨全局解释器锁(GIL)的影响及解决线程同步问题的最佳实践,如避免全局变量、使用线程安全数据结构、精细化锁的使用等。通过示例代码帮助开发者理解并提升多线程程序的性能与可靠性。
137 0
|
8天前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
78 0
|
3月前
|
数据采集 消息中间件 并行计算
Python多线程与多进程性能对比:从原理到实战的深度解析
在Python编程中,多线程与多进程是提升并发性能的关键手段。本文通过实验数据、代码示例和通俗比喻,深入解析两者在不同任务类型下的性能表现,帮助开发者科学选择并发策略,优化程序效率。
187 1
|
4月前
|
数据采集 监控 调度
干货分享“用 多线程 爬取数据”:单线程 + 协程的效率反超 3 倍,这才是 Python 异步的正确打开方式
在 Python 爬虫中,多线程因 GIL 和切换开销效率低下,而协程通过用户态调度实现高并发,大幅提升爬取效率。本文详解协程原理、实战对比多线程性能,并提供最佳实践,助你掌握异步爬虫核心技术。
|
4月前
|
数据采集 存储 Java
多线程Python爬虫:加速大规模学术文献采集
多线程Python爬虫:加速大规模学术文献采集
|
Python
Python Queue模块详解
来源:http://www.jb51.net/article/58004.htm Python中,队列是线程间最常用的交换数据的形式。Queue模块是提供队列操作的模块,虽然简单易用,但是不小心的话,还是会出现一些意外。 创建一个“队列”对象 import Queue q = Queue.Queue(maxsize = 10) Queue.Queue类即是一个队列
1949 0
|
机器学习/深度学习 安全 Python
第29天:Python queue 模块详解
第29天:Python queue 模块详解
464 0
|
Python
python --- queue模块使用
1. 什么是队列?   学过数据结构的人都知道,如果不知道队列,请Google(或百度)。 2. 在python中什么是多生产者,多消费模型?   简单来说,就是一边生产(多个生产者),一边消费(多个消费者)。
1243 0

推荐镜像

更多
下一篇
开通oss服务