多线程并发
概念: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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码