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的Tornado框架实现异步非阻塞访问数据库的示例
Jun 30 Python
使用Python进行二进制文件读写的简单方法(推荐)
Sep 12 Python
Python中装饰器兼容加括号和不加括号的写法详解
Jul 05 Python
python交互式图形编程实例(一)
Nov 17 Python
python正向最大匹配分词和逆向最大匹配分词的实例
Nov 14 Python
实例详解Python模块decimal
Jun 26 Python
Python多进程multiprocessing、进程池用法实例分析
Mar 24 Python
python根据完整路径获得盘名/路径名/文件名/文件扩展名的方法
Apr 22 Python
用于ETL的Python数据转换工具详解
Jul 21 Python
Python列表的深复制和浅复制示例详解
Feb 12 Python
用python删除文件夹中的重复图片(图片去重)
May 12 Python
Python利用FlashText算法实现替换字符串
Mar 31 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学习教程之第1天
2008/06/15 PHP
解析在PHP中使用全局变量的几种方法
2013/06/24 PHP
PHP简单预防sql注入的方法
2016/09/27 PHP
php/JS实现的生成随机密码(验证码)功能示例
2019/06/06 PHP
PHP7 参数处理机制修改
2021/03/09 PHP
js 颜色选择器(兼容firefox)
2009/03/05 Javascript
为Extjs加加速(javascript加速)
2010/08/19 Javascript
JavaScript中__proto__与prototype的关系深入理解
2012/12/04 Javascript
详解JavaScript语法对{}处理的坑爹之处
2014/06/05 Javascript
AngularJS 最常用的功能汇总
2016/02/17 Javascript
完美解决js传递参数中加号和&amp;号自动改变的方法
2016/10/11 Javascript
用jQuery的AJax实现异步访问、异步加载
2016/11/02 Javascript
bootstrap导航栏、下拉菜单、表单的简单应用实例解析
2017/01/06 Javascript
浅谈Angular6的服务和依赖注入
2018/06/27 Javascript
vue-cli项目无法用本机IP访问的解决方法
2018/09/20 Javascript
基于js实现判断浏览器类型代码实例
2020/07/17 Javascript
vue项目打包后提交到git上为什么没有dist这个文件的解决方法
2020/09/16 Javascript
[40:03]RNG vs VG 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
python中返回矩阵的行列方法
2018/04/04 Python
Diango + uwsgi + nginx项目部署的全过程(可外网访问)
2018/04/22 Python
使用python中的in ,not in来检查元素是不是在列表中的方法
2018/07/06 Python
python粘包问题及socket套接字编程详解
2019/06/29 Python
如何用Python做一个微信机器人自动拉群
2019/07/03 Python
win10下python2和python3共存问题解决方法
2019/12/23 Python
windows python3安装Jupyter Notebooks教程
2020/04/13 Python
Python获取excel内容及相关操作代码实例
2020/08/10 Python
有关pycharm登录github时有的时候会报错connection reset的问题
2020/09/15 Python
美国木工工具和用品商店:Woodcraft
2019/10/30 全球购物
海蓝之谜英国官网:La Mer英国
2020/01/15 全球购物
中软国际Java程序员笔试题
2014/07/19 面试题
求职推荐信
2013/10/28 职场文书
学生会主席事迹材料
2014/01/28 职场文书
主管会计岗位责任制
2014/02/10 职场文书
初中生入团申请书范文(五篇)
2019/10/16 职场文书
Redis 报错 error:NOAUTH Authentication required
2022/05/15 Redis
Windows11 Insider Preview Build 25206今日发布 更新内容汇总
2022/09/23 数码科技