博客
关于我
Python中的threading
阅读量:796 次
发布时间:2023-03-09

本文共 1792 字,大约阅读时间需要 5 分钟。

Python多线程编程实例分析

一、多线程基础与并行执行示例

在Python中,多线程编程可以通过threading模块实现。以下是一个简单的多线程并行执行示例:

import threadingimport timedef loop():    print('thread %s is running...' % threading.current_thread().name)    n = 0    while n < 5:        n += 1        print('thread %s ' % threading.current_thread().name)        time.sleep(3)    print('thread %s ended.' % threading.current_thread().name)print('thread %s is running...' % threading.current_thread().name)t = threading.Thread(target=loop, name='LoopThread')t.start()# t.join()print('thread %s ended.' % threading.current_thread().name)# 执行结果:# thread MainThread is running...# thread LoopThread is running...thread MainThread ended.# thread LoopThread# thread LoopThread# thread LoopThread# thread LoopThread# thread LoopThread ended.

结果分析

  • 主线程(MainThread)负责启动并管理子线程
  • 子线程(LoopThread)执行循环任务
  • 子线程与主线程并行运行,展示了多线程环境下的并行执行特性
  • 二、多线程与队列的结合应用

    以下是一个利用队列实现多线程间数据交互的实例:

    import Queueimport timeimport threadingimport randomq = Queue.Queue()def pro(name):    print("---pro data kaiqi")    time.sleep(3)    for i in range(20):        time.sleep(1)        print(name + "pro data" + str(i))        q.put(i)def con(name):    print("-----con data kaiqi")    n = 0    while n < 20:        time.sleep(3)        data = q.get()        print(name + "con data----" + str(data))        n += 1# 创建并启动子线程t1 = threading.Thread(group=None, target=pro, name=None, kwargs={'name':'laoban'})t2 = threading.Thread(group=None, target=con, name=None, kwargs={'name':'yuangong'})t1.start()t2.start()

    结果分析

  • 生产者线程(laoban):将数据放入队列
  • 消费者线程(yuangong):从队列中获取数据并处理
  • 两个线程并行运行,通过队列实现数据交互,展示了多线程环境下的异步通信机制
  • 三、多线程执行机制总结

    在Python中,多线程编程通过threading模块实现,核心原理是抢占式调度。以下是本文中两个示例的主要启示:

  • 多线程并行执行:主线程负责管理子线程的启动与等待,子线程则执行独立任务
  • 队列通信:通过队列实现线程间的数据交互,解决了多线程环境下的通信问题
  • 线程划分:合理划分线程任务,可以有效提高系统性能
  • 并行与串行特性:
    • 子线程任务(如j)可以并行执行
    • 队列处理(如i)需要串行执行
  • 转载地址:http://svlfk.baihongyu.com/

    你可能感兴趣的文章
    Python中制作词云的WordCloud参数详解
    查看>>
    Python中可用和使用的系统内存?
    查看>>
    python中存根文件(.pyi)的用途是什么?
    查看>>
    Python中实现ASCII码与字符相互转换
    查看>>
    Python中实现获取所有微信好友的头像并拼接成一张图片
    查看>>
    Python中对象的布尔值
    查看>>
    python中对集合的操作
    查看>>
    python中将列表转换为元组的时间复杂度,反之亦然
    查看>>
    Python中布尔表达式的求值
    查看>>
    python中很常用的10个内置函数整理(初学必备)
    查看>>
    python中打印二维列表数据
    查看>>
    python中打散数组shuffle
    查看>>
    Python中执行外部命令
    查看>>
    Python中拼接numpy数组-ChatGPT4o作答
    查看>>
    Python中提示:no module named 'PIL'
    查看>>
    Python中提示:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position
    查看>>
    python中数据类型存储_浅谈Python中的数据类型
    查看>>
    python中文件最重要的功能是什么-学 Python 都用来干嘛的?
    查看>>
    python中文版语言_高盛最新调查:Python超过汉语成为未来最重要技能,你准备学哪种编程语言?...
    查看>>
    Python中文问题SyntaxError
    查看>>