线程与进程应用场景

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

 

转载于:https://www.cnblogs.com/quqinchao/p/9323049.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值