Python多线程同步---文件读写控制方法


Posted in Python onFebruary 12, 2019

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 相关文章推荐
PyQt5打开文件对话框QFileDialog实例代码
Feb 07 Python
python PyTorch预训练示例
Feb 11 Python
python 删除非空文件夹的实例
Apr 26 Python
python cs架构实现简单文件传输
Mar 20 Python
很酷的python表白工具 你喜欢我吗
Apr 11 Python
使用python画社交网络图实例代码
Jul 10 Python
详解python statistics模块及函数用法
Oct 27 Python
Python求平面内点到直线距离的实现
Jan 19 Python
详解python中的lambda与sorted函数
Sep 04 Python
python 检测nginx服务邮件报警的脚本
Dec 31 Python
一个入门级python爬虫教程详解
Jan 27 Python
解决pycharm修改代码后第一次运行不生效的问题
Feb 06 Python
Python 按字典dict的键排序,并取出相应的键值放于list中的实例
Feb 12 #Python
Python 互换字典的键值对实例
Feb 12 #Python
Python根据成绩分析系统浅析
Feb 11 #Python
Python实现的在特定目录下导入模块功能分析
Feb 11 #Python
Python正则表达式和re库知识点总结
Feb 11 #Python
Python实现的大数据分析操作系统日志功能示例
Feb 11 #Python
Python实现对特定列表进行从小到大排序操作示例
Feb 11 #Python
You might like
珊瑚虫IP库浅析
2007/02/15 PHP
PHP中基于ts与nts版本- vc6和vc9编译版本的区别详解
2013/04/26 PHP
smarty内置函数config_load用法实例
2015/01/22 PHP
PHP实现的AES 128位加密算法示例
2019/09/16 PHP
PHP实现页面静态化深入讲解
2021/03/04 PHP
js确定对象类型方法
2012/03/30 Javascript
给js文件传参数(详解)
2014/07/13 Javascript
简单谈谈jQuery(function(){})与(function(){})(jQuery)
2014/12/19 Javascript
javascript包装对象实例分析
2015/03/27 Javascript
jQuery实现Meizu魅族官方网站的导航菜单效果
2015/09/14 Javascript
json与jsonp知识小结(推荐)
2016/08/16 Javascript
jQuery实现点击某个div打开层,点击其他div关闭层实例分析(阻止冒泡)
2016/11/18 Javascript
vue.js的手脚架vue-cli项目搭建的步骤
2017/08/30 Javascript
微信小程序实现图片上传功能
2018/05/28 Javascript
使用ng-packagr打包Angular的方法示例
2018/09/21 Javascript
Electron-vue脚手架改造vue项目的方法
2018/10/22 Javascript
浅谈js闭包理解
2019/04/01 Javascript
解决mui框架中switch开关通过js控制开或者关状态时小圆点不动的问题
2019/09/03 Javascript
[02:07]TI9显影之尘系列 - Vici Gaming
2019/08/20 DOTA
python使用cookielib库示例分享
2014/03/03 Python
Python中操作符重载用法分析
2016/04/29 Python
numpy.delete删除一列或多列的方法
2018/04/03 Python
Pandas之DataFrame对象的列和索引之间的转化
2019/06/25 Python
python 并发编程 多路复用IO模型详解
2019/08/20 Python
Python3.6实现根据电影名称(支持电视剧名称),获取下载链接的方法
2019/08/26 Python
墨尔本复古时尚品牌:Dangerfield
2018/12/12 全球购物
加拿大在线隐形眼镜和眼镜店:VisionPros
2019/10/06 全球购物
会计电算化应届生求职信
2013/11/03 职场文书
最新教师自我评价分享
2013/11/12 职场文书
计算机专业优秀大学生自我总结
2014/01/21 职场文书
法院信息化建设方案
2014/05/21 职场文书
三严三实对照检查材料
2014/08/25 职场文书
2014年安全管理工作总结
2014/12/01 职场文书
关于长城的导游词
2015/01/30 职场文书
聘任合同书
2015/09/21 职场文书
五年级数学教学反思
2016/02/16 职场文书