zoukankan      html  css  js  c++  java
  • 线程与进程应用场景

    1.计算密集型下进程与线程对比

    import  time,os
    from multiprocessing  import Process
    from threading import Thread
    #计算密集型
    def work():
        res= 0
        for i in range(100000):
            res+= i
    if __name__ == '__main__':
        l= []
        start= time.time()
        for i in range(4):
           # p= Process(target= work)  #0.3040175437927246
            p= Thread (target= work)  #0.047002553939819336
            l.append(p)
            p.start()
        for p in l:
            p.join()
        stop= time.time()
        print('run time is %s'%(stop-start))
    View Code

     2.IO密集型下进程与线程的对比

    from multiprocessing  import Process
    from threading import Thread
    def work1():
        time.sleep(2)
    def work2():
        time.sleep(2)
    def work3():
        time.sleep(2)
    if __name__ == '__main__':
        l= []
        start= time.time()
        # p1=Process (target= work1)   #2.2871310710906982
        # p2 = Process(target=work2)
        # p3 = Process(target=work3)
    
        t1= Thread (target= work1)    #2.018115282058716
        t2 = Thread(target=work2)
        t3 = Thread(target=work3)
        t1.start()
        t2.start()
        t3.start()
        t1.join()
        t2.join()
        t3.join()
        stop= time.time()
        print('run time is %s'%(stop- start))
    View Code

    3、定时器

    from threading import Timer,current_thread
    def task(x):
        print('%s run....' %x)
        print(current_thread().name) #打印进程名
    if __name__ == '__main__':
        t=Timer(3,task,args=(10,))
        t.start()
        print('')
    View Code

    4、进程queue方法

    (1)队列 先进先出queue.Queue

    q=queue.Queue(3)
    q.put(1)
    q.put(2)
    q.put(3)
    print(q.get())
    print(q.get())
    print(q.get())
    View Code

    (2)堆栈 先进后出 queue.LifoQueue

    import queue
    q=queue.LifoQueue()
    q.put(1)
    q.put(2)
    q.put(3)
    print(q.get())
    print(q.get())
    print(q.get())
    View Code

    (3)优先级队列:优先级高的先出来,数字越小,优先级越高

    q=queue.PriorityQueue()
    q.put((3,'data1'))
    q.put((-10,'data2'))
    q.put((11,'data3'))
    print(q.get())
    print(q.get())
    print(q.get())
    View Code
  • 相关阅读:
    php怎么实现多态?
    php怎么识别真实ip
    php析构函数什么时候调用?
    php解析xml的几种方式
    thinkPHP5框架路由常用知识点汇总
    用Python打造了一个渗透测试暴力探测器
    修复wecenter移动版description首页描述一样问题
    寒假小软件开发记录02--布局
    寒假小软件开发记录01--确定方向和素材准备
    大二上学期个人总结
  • 原文地址:https://www.cnblogs.com/quqinchao/p/9323049.html
Copyright © 2011-2022 走看看