python多线程同步之文件读写控制


Posted in Python onFebruary 25, 2021

本文实例为大家分享了python多线程同步之文件读写控制的具体代码,供大家参考,具体内容如下

1、实现文件读写的文件ltz_schedule_times.py

#! /usr/bin/env python
#coding=utf-8
import os

def ReadTimes():
 res = []
 if os.path.exists('schedule_times.txt'):
  fp = open('schedule_times.txt', 'r')
 else:
  os.system('touch schedule_times.txt')
  fp = open('schedule_times.txt', 'r')
 try:
  line = fp.read()
  if line == None or len(line)==0:
   fp.close()
   return 0
  tmp = line.split()
  print 'tmp: ', tmp
  schedule_times = int(tmp[-1])
 finally:
  fp.close()
 #print schedule_times
 return schedule_times

def WriteTimes(schedule_times):
 if schedule_times <= 10:
  fp = open('schedule_times.txt', 'a+')#10以内追加进去
 else:
  fp = open('schedule_times.txt', 'w')#10以外重新写入
  schedule_times = 1
 print 'write schedule_times start!'
 try:

  fp.write(str(schedule_times)+'\n')
 finally:
  fp.close()
  print 'write schedule_times finish!'

if __name__ == '__main__':

 schedule_times = ReadTimes()
 #if schedule_times > 10:
 # schedule_times = 0
 print schedule_times
 schedule_times = schedule_times + 1
 WriteTimes(schedule_times)

2.1、不加锁对文件进行多线程读写。file_lock.py

#! /usr/bin/env python
#coding=utf-8

from threading import Thread
import threading
import time
from ltz_schedule_times import *

#1、不加锁
def lock_test():
 time.sleep(0.1) 
 schedule_times = ReadTimes()
 print schedule_times
 schedule_times = schedule_times + 1
 WriteTimes(schedule_times)


if __name__ == '__main__':

 for i in range(5):
  Thread(target = lock_test, args=()).start()

得到结果:

0
write schedule_times start!
write schedule_times finish!
tmp: tmp: tmp: tmp:  [[[['1''1''1''1']]]]


11

1
 1
write schedule_times start!write schedule_times start!

write schedule_times start!write schedule_times start!

write schedule_times finish!
write schedule_times finish!
write schedule_times finish!write schedule_times finish!

文件写入结果:

python多线程同步之文件读写控制

以上结果可以看出,不加锁多线程读写文件会出现错误。

2.2、加锁对文件进行多线程读写。file_lock.py

#! /usr/bin/env python
#coding=utf-8

from threading import Thread
import threading
import time
from ltz_schedule_times import *

#2、加锁
mu = threading.Lock() #1、创建一个锁
def lock_test():
 #time.sleep(0.1) 
 if mu.acquire(True): #2、获取锁状态,一个线程有锁时,别的线程只能在外面等着
  schedule_times = ReadTimes()
  print schedule_times
  schedule_times = schedule_times + 1
  WriteTimes(schedule_times)
  mu.release() #3、释放锁  

if __name__ == '__main__':

 for i in range(5):
  Thread(target = lock_test, args=()).start()

结果:

0
write schedule_times start!
write schedule_times finish!
tmp: ['1']
1
write schedule_times start!
write schedule_times finish!
tmp: ['1', '2']
2
write schedule_times start!
write schedule_times finish!
tmp: ['1', '2', '3']
3
write schedule_times start!
write schedule_times finish!
tmp: ['1', '2', '3', '4']
4
write schedule_times start!
write schedule_times finish!

文件写入结果:

python多线程同步之文件读写控制

达到读写效果。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Python程序中进行文件读取和写入操作的教程
Apr 28 Python
Python自动化运维和部署项目工具Fabric使用实例
Sep 18 Python
Flask框架的学习指南之制作简单blog系统
Nov 20 Python
一篇文章快速了解Python的GIL
Jan 12 Python
pandas数据分组和聚合操作方法
Apr 11 Python
Python键盘输入转换为列表的实例
Jun 23 Python
python 实现求解字符串集的最长公共前缀方法
Jul 20 Python
详解pandas.DataFrame中删除包涵特定字符串所在的行
Apr 04 Python
Python3.5内置模块之random模块用法实例分析
Apr 26 Python
Python-接口开发入门解析
Aug 01 Python
Python Django中的STATIC_URL 设置和使用方式
Mar 27 Python
python给视频添加背景音乐并改变音量的具体方法
Jul 19 Python
python线程中的同步问题及解决方法
Aug 29 #Python
python实现H2O中的随机森林算法介绍及其项目实战
Aug 29 #Python
flask/django 动态查询表结构相同表名不同数据的Model实现方法
Aug 29 #Python
深入了解python中元类的相关知识
Aug 29 #Python
Django shell调试models输出的SQL语句方法
Aug 29 #Python
python实现文件的分割与合并
Aug 29 #Python
Python配置文件处理的方法教程
Aug 29 #Python
You might like
PHP无限分类的类
2007/01/02 PHP
php设计模式 Composite (组合模式)
2011/06/26 PHP
php + WebUploader实现图片批量上传功能
2019/05/06 PHP
php服务器的系统详解
2019/10/12 PHP
可缩放Reloaded-一个针对可缩放元素的复用组件
2007/03/10 Javascript
JavaScript 错误处理与调试经验总结
2010/08/10 Javascript
对javascript的一点点认识总结《javascript高级程序设计》读书笔记
2011/11/30 Javascript
jquery单行文字向上滚动效果示例
2014/03/06 Javascript
node.js 开发指南 ? Node.js 连接 MySQL 并进行数据库操作
2014/07/29 Javascript
jQuery插件编写步骤详解
2016/06/03 Javascript
如何获取元素的最终background-color
2017/02/06 Javascript
深入理解Node.js中通用基础设计模式
2017/09/19 Javascript
Vue父子模版传值及组件传值的三种方法
2017/11/27 Javascript
JS运动特效之同时运动实现方法分析
2018/01/24 Javascript
[02:22:36]《加油!DOTA》总决赛
2014/09/19 DOTA
[01:05:41]EG vs Optic Supermajor 败者组 BO3 第二场 6.6
2018/06/07 DOTA
python编程嵌套函数实例代码
2018/02/11 Python
python matplotlib 在指定的两个点之间连线方法
2018/05/25 Python
详解Anconda环境下载python包的教程(图形界面+命令行+pycharm安装)
2019/11/11 Python
用Python实现校园通知更新提醒功能
2019/11/23 Python
使用python写一个自动浏览文章的脚本实例
2019/12/05 Python
tensorflow 获取所有variable或tensor的name示例
2020/01/04 Python
Python如何在main中调用函数内的函数方式
2020/06/01 Python
python爬取抖音视频的实例分析
2021/01/19 Python
CSS3实现多重边框的方法总结
2016/05/31 HTML / CSS
西班牙拥有最佳品牌的动物商店:Animalear.com
2018/01/05 全球购物
美国在线医疗分销商:MedEx Supply
2020/02/04 全球购物
中间件分为哪几类
2012/03/14 面试题
致200米运动员广播稿
2014/02/06 职场文书
中国好声音广告词
2014/03/18 职场文书
水污染治理工程专业求职信
2014/06/14 职场文书
第二批党的群众路线教育实践活动总结报告
2014/10/30 职场文书
大学教师个人总结
2015/02/10 职场文书
爱的教育读书笔记
2015/06/26 职场文书
2016年九九重阳节活动总结
2016/04/01 职场文书
深入理解 Golang 的字符串
2022/05/04 Golang