線程與進程應用場景


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM