线程与进程应用场景

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

 

posted @ 2018-07-17 19:43  朝朝哥  阅读(1370)  评论(0编辑  收藏  举报