文件读写,多线程、多进程
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