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 相关文章推荐
pip 错误unused-command-line-argument-hard-error-in-future解决办法
Jun 01 Python
python网络编程学习笔记(三):socket网络服务器
Jun 09 Python
跟老齐学Python之有容乃大的list(2)
Sep 15 Python
Python与Redis的连接教程
Apr 22 Python
使用Python判断质数(素数)的简单方法讲解
May 05 Python
Python实现按中文排序的方法示例
Apr 25 Python
python实现移位加密和解密
Mar 22 Python
python实现批量视频分帧、保存视频帧
May 31 Python
Django框架组成结构、基本概念与文件功能分析
Jul 30 Python
python元组的概念知识点
Nov 19 Python
python opencv图片编码为h264文件的实例
Dec 12 Python
解决运行出现'dict' object has no attribute 'has_key'问题
Jul 15 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与SQL注入攻击[一]
2007/04/17 PHP
php-accelerator网站加速PHP缓冲的方法
2008/07/30 PHP
php面向对象全攻略 (十六) 对象的串行化
2009/09/30 PHP
为PHP初学者的8点有效建议
2010/11/20 PHP
CodeIgniter分页类pagination使用方法示例
2016/03/28 PHP
PHP使用星号替代用户名手机和邮箱的实现代码
2018/02/07 PHP
php生成二维码不保存服务器还有下载功能的实现代码
2018/08/09 PHP
PHP生成随机密码4种方法及性能对比
2020/12/11 PHP
javascript firefox不显示本地预览图片问题的解决方法
2008/11/12 Javascript
javascript实现十六进制颜色值(HEX)和RGB格式相互转换
2014/06/20 Javascript
JQuery中Text方法用法实例分析
2015/05/18 Javascript
jquery实现平滑的二级下拉菜单效果
2015/08/26 Javascript
jQuery+PHP+MySQL二级联动下拉菜单实例讲解
2015/10/27 Javascript
js弹出对话框方式小结
2015/11/17 Javascript
AngularJS中监视Scope变量以及外部调用Scope方法
2016/01/23 Javascript
javascript创建对象、对象继承的实用方式详解
2016/03/08 Javascript
AngularJS实用开发技巧(推荐)
2016/07/13 Javascript
总结十个Angular.js由浅入深的面试问题
2016/08/26 Javascript
基于Vue2实现的仿手机QQ单页面应用功能(接入聊天机器人 )
2017/03/30 Javascript
Nodejs异步回调之异常处理实例分析
2018/06/22 NodeJs
vue 使用element-ui中的Notification自定义按钮并实现关闭功能及如何处理多个通知
2019/08/17 Javascript
基于layui的下拉列表的数据回显方法
2019/09/24 Javascript
基于Element的组件改造的树形选择器(树形下拉框)
2020/02/27 Javascript
[12:36]《DOTA2》国服注册与激活指南全攻略
2013/04/28 DOTA
简单的编程0基础下Python入门指引
2015/04/01 Python
说一说Python logging
2016/04/15 Python
Python爬虫利用cookie实现模拟登陆实例详解
2017/01/12 Python
PyCharm+PySpark远程调试的环境配置的方法
2018/11/29 Python
Django使用list对单个或者多个字段求values值实例
2020/03/31 Python
PyPDF2读取PDF文件内容保存到本地TXT实例
2020/05/12 Python
Django model.py表单设置默认值允许为空的操作
2020/05/19 Python
美国床垫和床上用品公司:Nest Bedding
2017/06/12 全球购物
党日活动总结
2014/05/07 职场文书
临时用工协议书范本
2014/10/29 职场文书
节水宣传标语口号
2015/12/26 职场文书
2019通用版劳动合同范本!
2019/07/11 职场文书