python使用多线程写入数据到文件
2023-09-11 14:15:15 时间
python使用多线程写入数据时,可能会存在写入的一些数据丢失现象。如示例代码1所示,反复修改写入文件的两种方式和加入buffering缓冲也时存在数据丢失现象。
示例代码1:
import time
import threading
from queue import Queue
def func(num):
time.sleep(1)
thread_name = threading.current_thread().name
data = str(num) + "当前线程:" + thread_name + '\n'
print(data)
with open('text.txt', 'a', encoding='utf-8') as f:
f.write(data)
# f = open('text.txt', 'a', encoding='utf-8', buffering=100)
# f.write(data)
# f.close()
if __name__ == '__main__':
queue = Queue()
for i in range(1000):
queue.put(i)
# 开启100个线程
for _ in range(100):
thread = threading.Thread(target=func, args=(queue.get(),))
thread.start()
运行结果:
百度众多帖子也未找到答案,最后加入了锁机制,竟然解决了数据丢失的问题!如示例代码2所示。
示例代码2:
import time
import threading
from queue import Queue
from threading import Lock
mutex = Lock()
def func(num):
time.sleep(1)
thread_name = threading.current_thread().name
data = str(num) + "当前线程:" + thread_name + '\n'
print(data)
mutex.acquire()
with open('text.txt', 'a', encoding='utf-8') as f:
f.write(data)
mutex.release()
# f = open('text.txt', 'a', encoding='utf-8', buffering=100)
# f.write(data)
# f.close()
if __name__ == '__main__':
queue = Queue()
for i in range(10000):
queue.put(i)
# 开启10000个线程
for _ in range(10000):
thread = threading.Thread(target=func, args=(queue.get(),))
thread.start()
运行结果:
各位大佬若有好的办法,欢迎评论区留言......
相关文章
- Python 中 xpath 语法 与 lxml 库解析 HTML/XML 和 CSS Selector
- python安装python-lzf包,报错lzf_module.c:3:20: fatal error: Python.h: No such file or directory
- python通过ssh连接mysql数据库的注意事项
- Python删除文件、删除文件夹
- Python 使用ntplib库同步校准当地时间的方法 (NTP)
- Google Earth Engine——使用 Leaflet 和 Folium 在 Python 中制作交互式地图
- python内置函数next()方法用法详解
- python强大之处在哪里?为什么那么多人喜欢Python?
- Python 读取 .mdb文件信息
- 最适合学Python的五类人,有你吗?
- python之模块csv之CSV文件的写入(基本结构)
- 《Python极客项目编程 》——第一部分 热身运动 第1章 解析iTunes播放列表 1.1 iTunes播放列表文件剖析
- 《Python Cookbook(第3版)中文版》——1.15 根据字段将记录分组
- 《Python 3程序开发指南(第2版•修订版)》——7.3 写入与分析XML文件
- Python遍历文件,重命名
- 基于Python(Django)+MySQL 实现(Web)SQL智能检测系统的设计与实现【100010694】
- Python数据可视化 Pyecharts 制作 Map3D 三维地图
- python中的if判断语句
- Python NVIDIA Isaac机器人平台开发教程之 01 什么是NVIDIA Isaac
- Python 数据分析教程之如何验证线性回归的假设,线性回归的假设是什么?以及如何用python验证它们?
- Python绘制RTKLIB结果文件.pos源码
- Python中向矩阵中增加几行或几列元素
- 解决jupyter的能打开python文件无法新建的问题
- Python 取样式的内容 合并多个文件的样式 自定义样式
- Python无法导入Cython的.pyx文件
- [Python] if __name__ == ‘__main__‘的作用