Python练习笔记(2)
2024-08-25 18:05:16
文件读写,多线程、多进程
import time,os,threading,random def file_read(path):
try:
with open(path, 'r') as f:
# str = f.read()
# print(str)
for line in f.readlines():
print(line.strip()) # while True:
# l = f.readline()
# if l == '':
# break
# print(l.strip())
except Exception as e:
print('Error: ', e) def file_write(path, str):
try:
with open(path, 'a') as f:
f.write(str)
except Exception as e:
print('Error: ', e)
# 文件读写
# file_write('d:/test.txt', time.strftime('%Y-%m-%d %H:%M:%S')+' test\n')
# file_read('d:/test.txt') # 多线程 多进程
import multiprocessing
lock = threading.Lock()
def run_thread1():
lock.acquire()
print('Process (%s) thread %s is running...' % (os.getpid(), threading.current_thread().name))
time.sleep(3)
lock.release() def run_thread2():
lock.acquire()
print('Process (%s) thread %s is running...' % (os.getpid(), threading.current_thread().name))
time.sleep(1)
lock.release() def long_time_task(name):
print('Run task %s (%s)...' % (name, os.getpid()))
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print('Task %s runs %0.2f seconds.' % (name, (end - start))) if __name__ == '__main__':
t1 = threading.Thread(target=run_thread1)
t2 = threading.Thread(target=run_thread2, name='Jincheng2')
t1.start()
t2.start()
t1.join()
t2.join() p1 = multiprocessing.Process(target=run_thread1)
p1.start()
p1.join() # 进程池创建子进程
p = multiprocessing.Pool(4)
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
# 子进程subprocess,进程间通信Queue、Pipes
最新文章
- yield生成器及字符串的格式化
- SecureCRT上传、下载文件(使用sz与rz命令)
- buffer busy wait在RAC环境下出现
- javascript基础之javascript的存在形式和js代码块在页面中的存放位置
- spark aggregate
- html标签总结。
- Android核心基础(十一)
- python3操作socketserver
- Wpf DataGrid 自动滚动到最后一行
- 2017 Russian Code Cup (RCC 17), Final Round
- 20165205 学习基础与C语言基础调查
- 在eclipse-oxygen-sts中,关于快捷键[CTRL + SHIFT + O]失效的问题
- Java常考面试题(二)
- Java如何格式化月份?
- 2018牛客网暑期ACM多校训练营(第三场) A - PACM Team - [四维01背包][四约束01背包]
- 如何使用swingbench进行oracle数据库压力测试
- jquery取iframe中元素
- 设置eclipse显示代码错误提示的
- npm i -S -D -g 区别
- C# Enum,Int,String,之间及bool与int之间的转换