栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python编程实践 - 多线程

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python编程实践 - 多线程

简介

本文介绍在Python中如何实现多线程,包含如下要点:

  1. 面向对象的继承,实现自定义的多线程类
  2. 队列的使用,包括队列的初始化、赋值、取数
一、 面向对象的继承,实现自定义的多线程类

继承threading.Thread类,并实现__init__方法和run方法

class myThread (threading.Thread):
    def __init__(self, threadID, threadName, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.threadName = threadName
        self.q = q
    def run(self):
        print ("开启线程:" + self.name)
        self.process_data()
        print ("退出线程:" + self.name)
二、 队列的使用

队列的特性是先进先出,可保证处理的顺序性。如果没有顺序性的要求,也可以用列表、数组等来替代。

    # 队列初始化,队列大小有日期列表的长度而定
    work_queue = queue.Queue(len(date_list))
    # 队列赋值
    for word in date_list:
        work_queue.put(word)
    # 队列中取数
    data = work_queue.get()
完整代码
# coding=utf-8
import os
import string
import pandas as pd
import queue
import threading
import time

class MyThread (threading.Thread):
    def __init__(self, thread_id, thread_name, work_queue):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.thread_name = thread_name
        self.work_queue = work_queue
    def run(self):
        print ("开启线程:" + self.thread_name)
        self.process_data()
        print ("退出线程:" + self.thread_name)

    def process_data(self):
        while not exitFlag:
            if not self.work_queue.empty():
                ## 从队列中取出一个数据对象
                data = self.work_queue.get()
                print ("%s processing %s" % (self.thread_name, data))
            time.sleep(1)

if __name__ == '__main__':
    ## 用于标识是否结束线程,当exitFlag = 1时,结束线程
    exitFlag = 0
    thread_num = 3
    start_date = '20210101'
    end_date = '20210201'
    date_list = pd.date_range(start=start_date, end=end_date, freq="D")
    # 队列初始化,队列大小有日期列表的长度而定
    work_queue = queue.Queue(len(date_list))
    # 队列赋值
    for word in date_list:
        work_queue.put(word)


    threads = []
    # 创建新线程
    for thread_id in range(1, thread_num+1):
        thread_name = 'Thread-%d'%thread_id
        thread = MyThread(thread_id, thread_name, work_queue)
        thread.start()
        threads.append(thread)



    # 等待队列清空
    while not work_queue.empty():
        pass

    # 通知线程是时候退出
    exitFlag = 1

    # 等待所有线程完成
    for t in threads:
        t.join()
    print ("退出主线程")
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/935615.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号