Python练习笔记(2)

文件读写,多线程、多进程

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

  

 

转载于:https://www.cnblogs.com/wqiwen/p/9776699.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值