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使用any判断一个对象是否为空的方法
Nov 19 Python
python决策树之C4.5算法详解
Dec 20 Python
浅谈python配置与使用OpenCV踩的一些坑
Apr 02 Python
Python面向对象类的继承实例详解
Jun 27 Python
Python PyAutoGUI模块控制鼠标和键盘实现自动化任务详解
Sep 04 Python
Python文件监听工具pyinotify与watchdog实例
Oct 15 Python
PyCharm+Qt Designer+PyUIC安装配置教程详解
Jun 13 Python
python批量将excel内容进行翻译写入功能
Oct 10 Python
Tensorflow 定义变量,函数,数值计算等名字的更新方式
Feb 10 Python
Python 如何实现访问者模式
Jul 28 Python
详解python os.path.exists判断文件或文件夹是否存在
Nov 16 Python
matplotlib绘制鼠标的十字光标的实现(内置方式)
Jan 06 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中将图片gif,jpg或mysql longblob或blob字段值转换成16进制字符串
2011/08/23 PHP
php实现执行某一操作时弹出确认、取消对话框
2013/12/30 PHP
php获取根域名方法汇总
2014/10/28 PHP
PHP 二维数组和三维数组的过滤
2016/03/16 PHP
PHP读取word文档的方法分析【基于COM组件】
2017/08/01 PHP
PHP钩子与简单分发方式实例分析
2017/09/04 PHP
php微信支付之公众号支付功能
2018/05/30 PHP
Jquery为a标签的href赋值实现代码
2013/05/03 Javascript
jQuery cdn使用介绍
2013/05/08 Javascript
火狐textarea输入法的bug的触发及解决
2013/07/24 Javascript
js判断undefined类型,undefined,null, 的区别详细解析
2013/12/16 Javascript
js的Boolean对象初始值示例
2014/03/04 Javascript
点击表单提交时出现jQuery没有权限的解决方法
2014/07/23 Javascript
在JavaScript应用中使用RequireJS来实现延迟加载
2015/07/01 Javascript
浅析使用BootStrap TreeView插件实现灵活配置快递模板
2016/11/28 Javascript
使用angular帮你实现拖拽的示例
2017/07/05 Javascript
详解webpack + vue + node 打造单页面(入门篇)
2017/09/23 Javascript
node.js自动上传ftp的脚本分享
2018/06/16 Javascript
vue解决使用webpack打包后keep-alive不生效的方法
2018/09/01 Javascript
Vue 实现复制功能,不需要任何结构内容直接复制方式
2019/11/09 Javascript
简单了解vue 插值表达式Mustache
2020/07/22 Javascript
Vue按时间段查询数据组件使用详解
2020/08/21 Javascript
python anaconda 安装 环境变量 升级 以及特殊库安装的方法
2017/06/21 Python
Scrapy抓取京东商品、豆瓣电影及代码分享
2017/11/23 Python
Pandas:Series和DataFrame删除指定轴上数据的方法
2018/11/10 Python
Python中如何使用if语句处理列表实例代码
2019/02/24 Python
Python定义一个Actor任务
2020/07/29 Python
简单了解Python字典copy与赋值的区别
2020/09/16 Python
css3+伪元素实现鼠标移入时下划线向两边展开的效果
2017/04/25 HTML / CSS
CSS3的 fit-content实现水平居中
2017/09/07 HTML / CSS
日本7net购物网:书籍、漫画、杂志、DVD、游戏邮购
2017/02/17 全球购物
澳洲本土太阳镜品牌:Quay Australia
2019/07/29 全球购物
基督教婚礼主持词
2014/03/14 职场文书
建筑工地资料员岗位职责
2015/04/13 职场文书
酒店工程部主管岗位职责
2015/04/16 职场文书
MySQL慢查询的坑
2021/04/28 MySQL