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 相关文章推荐
Python日志模块logging简介
Apr 13 Python
Python聚类算法之DBSACN实例分析
Nov 20 Python
详解tensorflow训练自己的数据集实现CNN图像分类
Feb 07 Python
Python中协程用法代码详解
Feb 10 Python
多个应用共存的Django配置方法
May 30 Python
Python3.8中使用f-strings调试
May 22 Python
Django中reverse反转并且传递参数的方法
Aug 06 Python
解决python3插入mysql时内容带有引号的问题
Mar 02 Python
python字典通过值反查键的实现(简洁写法)
Sep 30 Python
Django限制API访问频率常用方法解析
Oct 12 Python
用python自动生成日历
Apr 24 Python
python实现的人脸识别打卡系统
May 08 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
在服务端进行目录建立、删除,文件上传、删除的过程的php代码
2008/09/10 PHP
无法载入 mcrypt 扩展,请检查 PHP 配置终极解决方案
2011/07/18 PHP
浅谈PHPANALYSIS提取关键字
2019/03/08 PHP
Git命令之分支详解
2021/03/02 PHP
有一段有意思的代码-javascript现实多行信息
2007/08/26 Javascript
JS window.opener返回父页面的应用
2009/10/24 Javascript
JQuery 构建客户/服务分离的链接模型中Table分页代码效率初探
2010/01/22 Javascript
jQuery 淡入淡出 png图在ie8下有黑色边框的解决方法
2013/03/05 Javascript
为JS扩展Array.prototype.indexOf引发的问题及解决办法
2015/01/21 Javascript
ECMAScript 5中的属性描述符详解
2015/03/02 Javascript
理解JavaScript事件对象
2016/01/25 Javascript
js模态对话框使用方法详解
2017/02/16 Javascript
Angular.js与node.js项目里用cookie校验账户登录详解
2017/02/22 Javascript
js实现拖拽上传图片功能
2017/08/01 Javascript
详解vue中async-await的使用误区
2018/12/05 Javascript
细说Vue组件的服务器端渲染的过程
2019/05/30 Javascript
vue实现一拉到底的滑动验证
2019/07/25 Javascript
Javascript操作select控件代码实例
2020/02/14 Javascript
JavaScript缓动动画函数的封装方法
2020/11/25 Javascript
Python实现Linux的find命令实例分享
2017/06/04 Python
详解用python自制微信机器人,定时发送天气预报
2019/03/25 Python
python使用mitmproxy抓取浏览器请求的方法
2019/07/02 Python
用Python实现二叉树、二叉树非递归遍历及绘制的例子
2019/08/09 Python
python实现从wind导入数据
2019/12/03 Python
Python3之乱码\xe6\x97\xa0\xe6\xb3\x95处理方式
2020/05/11 Python
Python如何解除一个装饰器
2020/08/07 Python
如何使用PyCharm引入需要使用的包的方法
2020/09/22 Python
使用python将微信image下.dat文件解密为.png的方法
2020/11/30 Python
python pygame 愤怒的小鸟游戏示例代码
2021/02/25 Python
Ray-Ban雷朋瑞典官方网站:全球领先的太阳眼镜品牌
2019/08/22 全球购物
用C#语言写出在本地创建一个UDP接收端口的具体过程
2016/02/22 面试题
校运动会广播稿(100篇)
2014/09/12 职场文书
2014党员四风对照检查材料思想汇报
2014/09/17 职场文书
初中生毕业评语
2014/12/29 职场文书
乔迁新居祝福语
2019/11/04 职场文书
JAVA SpringMVC实现自定义拦截器
2022/03/16 Python