线程与进程应用场景
程序员文章站
2022-03-05 16:53:42
...
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))
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))
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('主')
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())
(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())
(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())