• 面对密集型的I/O任务处理,python该如何提高执行效率


    密集型的I/O任务最常见的就是经常需要轮询去读取或下载数据文件,并且I/O的密集程度是相当高的。

    若是碰到类似这样的业务处理,单线程的串行处理效率无疑是比较低的,这个时候首先应该想到的就是多线程的方式的来解决问题。

    这里就通过python内置的多线程来解决一个读取批量数据文件内容的业务场景,我相信这样的场景肯定也是大家在开发商过程中经常遇到的,话不多说,直接开干。

    import threadingpython
    
    • 1

    1、创建基础函数

    首先,开发一个数据文件的读取函数,用来专门读取文件数据内容。

    def read_file_data(n=0):
        '''
        读取txt文件
        :param n:
        :return:
        '''
        with open('数据_{}.txt'.format(n), encoding='utf-8') as file:
            content = file.read()  # 读取文件内容
            print(content.rstrip())  # 删除末尾空行
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    接着,开发一个数据文件的写入函数,专门向文件中写入内容。

    def write_file_data(n=0, content='文件内容'):
        '''
        写入txt文件
        :param n:
        :param content:
        :return:
        '''
        with open('数据_{}.txt'.format(n), 'a') as file:
            file.write(content + '\n')
            print('{}内容已写入!'.format(content))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2、创建多线程

    初始化文件读取及文件内容写入多线程的存储数组,分别为read_threads和write_threads。

    read_threads = []
    
    write_threads = []
    
    • 1
    • 2
    • 3

    初始化文件读取线程并绑定线程执行的文件读取函数,将初始化完成的线程存储到read_threads线程数组中。

    for n in range(1, 5):
        t = threading.Thread(target=read_file_data, args=(n,))
        t.setDaemon(True)
        read_threads.append(t)
    
    • 1
    • 2
    • 3
    • 4

    初始化文件写入线程并绑定线程执行的文件写入函数,将初始化完成的线程存储到write_threads线程数组中。

    for n in range(1, 3):
        t = threading.Thread(target=write_file_data, args=(n, 'Python is Good !',))
        t.setDaemon(True)
        write_threads.append(t)
    
    • 1
    • 2
    • 3
    • 4

    分别启动read_threads、write_threads数组中存储的文件读取以及文件写入的多线程任务,并加入线程等待。

    for t in read_threads:
        t.start()
    
    for t in read_threads:
        t.join()
    
    for t in write_threads:
        t.start()
    
    for t in write_threads:
        t.join()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    上面在过程中,做数据读取时调用了4个txt的数据文件,写入时则调用了2个txt数据文件,启动后整个过程基本都是瞬间完成。

  • 相关阅读:
    Spark的数据输入、数据计算、数据输出
    vue3和vue2 的区别,vue3和vu2到底哪个好呢?
    蓝桥等考Python组别六级003
    网工内推 | 国企、港企网工,年底双薪,NA以上认证即可
    【学习笔记】《Python深度学习》第五章:深度学习用于计算机视觉
    【Maven】Unsupported major.minor version 52.0
    怎么在OPPO手机桌面上添加文字?便签桌面插件添加教程
    给电脑重装系统后修改远程桌面端口的方法
    业务开发流程
    苹果对高通说:我4.45亿美元买下一个新园区,可能计划加快基带芯片自研
  • 原文地址:https://blog.csdn.net/chengxuyuan_110/article/details/126897551