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 socket网络编程TCP/IP服务器与客户端通信
Jan 05 Python
flask + pymysql操作Mysql数据库的实例
Nov 13 Python
python 列表降维的实例讲解
Jun 28 Python
通过Python模块filecmp 对文件比较的实现方法
Jun 29 Python
对matplotlib改变colorbar位置和方向的方法详解
Dec 13 Python
Python定义函数功能与用法实例详解
Apr 08 Python
python画图把时间作为横坐标的方法
Jul 07 Python
python Web flask 视图内容和模板实现代码
Aug 23 Python
python psutil监控进程实例
Dec 17 Python
Pycharm新手使用教程(图文详解)
Sep 17 Python
改变 Python 中线程执行顺序的方法
Sep 24 Python
python周期任务调度工具Schedule使用详解
Nov 23 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
虹吸壶是谁发明的?煮出来的咖啡好喝吗
2021/03/04 冲泡冲煮
jQuery+php简单实现全选删除的方法
2016/11/28 PHP
经验几则 推荐
2006/09/05 Javascript
javascript读取RSS数据
2007/01/20 Javascript
IE8 引入跨站数据获取功能说明
2008/07/22 Javascript
javascript简易缓动插件(源码打包)
2012/02/16 Javascript
jQuery Deferred和Promise创建响应式应用程序详细介绍
2013/03/05 Javascript
完美解决IE低版本不支持call与apply的问题
2013/12/05 Javascript
JS控制表格实现一条光线流动分割行的方法
2015/03/09 Javascript
jQuery实现鼠标滑过链接控制图片的滑动展开与隐藏效果
2015/10/28 Javascript
JQuery datepicker 用法详解
2015/12/25 Javascript
原生js实现密码输入框值的显示隐藏
2017/07/17 Javascript
react 父子组件之间通讯props
2018/09/08 Javascript
Vue 全家桶实现移动端酷狗音乐功能
2018/11/16 Javascript
Jquery让form表单异步提交代码实现
2019/11/14 jQuery
不刷新网页就能链接新的js文件方法总结
2020/03/01 Javascript
原生js+canvas实现验证码
2020/11/29 Javascript
[03:42]2016国际邀请赛中国区预选赛首日现场玩家采访
2016/06/26 DOTA
Python每天必学之bytes字节
2016/01/28 Python
深入理解Python中装饰器的用法
2016/06/28 Python
对numpy.append()里的axis的用法详解
2018/06/28 Python
Python matplotlib的使用并自定义colormap的方法
2018/12/13 Python
python调试神器PySnooper的使用
2019/07/03 Python
Python实现决策树并且使用Graphviz可视化的例子
2019/08/09 Python
Python底层封装实现方法详解
2020/01/22 Python
Python实现进度条和时间预估的示例代码
2020/06/02 Python
基于Python爬取股票数据过程详解
2020/10/21 Python
python实现不同数据库间数据同步功能
2021/02/25 Python
西班牙在线药店:DosFarma
2020/03/28 全球购物
PyQt 如何创建自定义QWidget
2021/03/24 Python
党员四风问题对照检查材料
2014/09/27 职场文书
在教室放鞭炮的检讨书
2014/09/28 职场文书
锅炉工岗位职责
2015/02/13 职场文书
博士生专家推荐信
2015/03/25 职场文书
Python绘制地图神器folium的新人入门指南
2021/05/23 Python
十大必看国产动漫排名,魁拔上线,第二曾在日本播出
2022/03/18 国漫