多线程并发

概念:https://www.liaoxuefeng.com/wiki/1016959663602400/1017629247922688
示例:https://blog.csdn.net/will130/article/details/50599577

1、多线程分别读取写入多个文件

#! /usr/bin/env python
#coding=utf-8
from threading import Thread
import threading
import time
import os

file_dict = '/Users/Downloads'


#多线程分别读取和写入多个文件
def file_io(thread_index):
    outfile_path = file_dict + '/thread_output_' + str(thread_index) + '.txt'
    outfile = open(outfile_path, 'w')

    infile_path = file_dict + '/thread_input_' + str(thread_index) + '.txt'
    with open(infile_path, 'r') as infile:
        line = infile.readline()
        while line:
            outfile.write(line)
            #print(line)
            line = infile.readline()

    outfile.close()
    print(threading.current_thread().name + ': write schedule_times finish!')


def loop():
    thread_index = int(threading.current_thread().name.split('_')[1])
    print('thread %s is running...' % threading.current_thread().name)
    file_io(thread_index)


if __name__ == '__main__':
    for i in range(3):
        Thread(target=loop, name='thread_' + str(i), args=()).start()


注意:对于服务耗时长的情况,注意需要把服务超时设置足够大,否则可能报错: httpcore.ReadError: [Errno 104] Connection reset by peer

posted @   chease  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示