博客
关于我
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中的多个元组到两对元组?
    查看>>
    Python中的多态性
    查看>>