python的多线程和多进程

#from multiprocessing import Process,multiprocessing
#import threading,time
#import os,time
#print(multiprocessing.cpu_count());
from multiprocessing import Pool
import os, time, random
#cpu_count=multiprocessing.cpu_count()
def video_work(n):
	print("video start")
	for i in range(4):
		print(' video:%s' % time.time())
	print('video end')		
def voice_work(n):
	print('voice start')
	for i in range(4):
		print(' voice:%s' % time.time())
	print('voice end')		
def text_work(n):
	print('text start')
	for i in range(4):
		print(' text:%s' % time.time())
	print('text end')
if __name__=='__main__':
	print("movie start")
	p=Pool(3)
	p.apply_async(video_work, args=(1,))
	p.apply_async(voice_work, args=(1,))
	p.apply_async(text_work, args=(1,))
	print("movie end")
	p.close()
	p.join()
os._exit(0);
#下面是多线程
def video_work(n):
	print("video start")
	for i in range(4):
		print(' video:%s' % time.time())
	print('video end')		
def voice_work(n):
	print('voice start')
	for i in range(4):
		print(' voice:%s' % time.time())
	print('voice end')		
def text_work(n):
	print('text start')
	for i in range(4):
		print(' text:%s' % time.time())
	print('text end')		
vi=threading.Thread(target=video_work, args=(5,))
vo=threading.Thread(target=voice_work, args=(5,))
te=threading.Thread(target=text_work, args=(5,))

vi.start()
vo.start()
te.start()
vi.join()
vo.join()
te.join()

下面赋上进程和线程的结果对比:
线程:
video start
 video:1514341023.8669481
 video:1514341023.866982
 video:1514341023.8669922
 video:1514341023.867
video end
voice start
 voice:1514341023.867081
 voice:1514341023.867098
 voice:1514341023.867109
 voice:1514341023.867122
voice end
text start
 text:1514341023.867318
 text:1514341023.86733
 text:1514341023.8673432
 text:1514341023.8673549
text end
[Finished in 0.2s]
进程:
movie start
movie end
video start
 video:1514340229.850396
 video:1514340229.850455
 video:1514340229.850463
voice start
 video:1514340229.8504698
video end
 voice:1514340229.850525
 voice:1514340229.8505862
 voice:1514340229.8505971
 voice:1514340229.850604
voice end
text start
 text:1514340229.851182
 text:1514340229.85122
 text:1514340229.85123
 text:1514340229.851239
text end
[Finished in 0.3s]
进程是真正的做到了并发。而多线程并发因为锁的原因,并不能做到这一点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值