zoukankan      html  css  js  c++  java
  • python_线程读写操作<一>

    线程读写操作

    import threading,random,queue
    q = queue.Queue()
    alist=[]
    def shengchan():
        for i in range(10):
            alist.append(random.randint(1,20))
        q.put(alist)
        print('随机生成的十个数是%s'%alist)
    def xiaofei():
        with open('xiabo.txt','w+',encoding='utf8') as f:
            f.write(str(q.get()))
            f.seek(0)
            c =f.read()
            print(c)
    if __name__=='__main__':
        t1 = threading.Thread(target=shengchan)
        t2 = threading.Thread(target=xiaofei)
        t1.start()
        t2.start()

    进程池相关

    from multiprocessing import Pool  # 导入模块进程池
    import os, time, random  # 导入windows系统,时间,随机数模块
    
    
    # print(random.random())
    def task(name):  # name是一个形参,先分析函数功能
        print('任务跑在 %s (%d)...' % (name, os.getpid()))  # 打印了进程池传的参数i,还有进程编号
        start = time.time()  # 记录一个开始时间
        time.sleep(random.random() * 3)  # 随机0-3之间的数
        # print(random.random()*3) %s 字符串 %d 整型 %f 浮点型
        end = time.time()  # 结束时间
        print('任务 %s 跑了 %0.2f时间' % (name, (end - start)))  # 结束减去开始时间可以得出跑了多长时间算出函数运行时间
    
    
    if __name__ == '__main__':
        print('父进程是%d' % os.getpid())  # 获取当前进程编号ID
        p = Pool(4)  # 使用进程池类方法创建了4个进程
        for i in range(1, 6):  # 给4个进程分派了5个任务任务编号是1,2,3,4,5
            p.apply_async(task, args=(i,))  # apply_async 是异步非阻塞的。# 让进程池执行了task函数,传的参数是i
        # 意思就是:不用等待当前进程执行完毕,随时根据系统调度来进行进程切换。
        print('等待所有子进程跑完...')
        p.close()  # 关闭进程池,因为后边有join必须保证子进程不再乱跑
        # time.sleep(2)
        # p.join()  # 让所有的进程互相等待大家一起结束回家吃饭
        print('所有的子进程跑完了')
  • 相关阅读:
    [leetcode]Remove Nth Node From End of List
    [leetcode]Palindrome Number
    [leetcode]Integer to Roman
    HDU 4709:Herding
    HDU 4708:Rotation Lock Puzzle
    HDU 4707:Pet
    HDU 4706:Children's Day
    SDUT 2411:Pixel density
    SDUT 2413:n a^o7 !
    SDUT 2409:The Best Seat in ACM Contest
  • 原文地址:https://www.cnblogs.com/zhichao123/p/11240842.html
Copyright © 2011-2022 走看看