线程代码:
import threading import time Lock = threading.Lock() def worker(i): Lock.acquire() print(threading.current_thread().name,"上锁!") time.sleep(5) print("获得的数据是:",i) Lock.release() print(threading.current_thread().name,"解锁!") if __name__ == '__main__': start = time.time() Thread_List = [] for i in range(10): t = threading.Thread(target=worker,args=(i,)) Thread_List.append(t) for t in Thread_List: t.start() for t in Thread_List: t.join() end = time.time() print('完毕,用时:%s'%(end-start))
进程代码:
import multiprocessing import time def worker(data,Semap): Semap.acquire() print(multiprocessing.current_process().name,"上锁!") time.sleep(5) print('获得的数据是:',data) Semap.release() print(multiprocessing.current_process().name,'解锁!') if __name__ == '__main__': start = time.time() Process_List = [] Semap = multiprocessing.Semaphore(5) for i in range(10): t = multiprocessing.Process(target=worker, args=(i,Semap)) Process_List.append(t) for t in Process_List: t.start() for t in Process_List: t.join() end = time.time() print('完毕,用时:%s' % (end - start))
实验: 两个文件同时进行跑,看看哪个Python文件先跑完!
进程执行效果图:
线程执行效果图:
同样是在函数执行的过程中进行了休眠5秒,然而执行之后的结果却是让人大跌眼镜!
由于Python的GIL全局解释器锁的存在,线程的性能被大打则扣.因为这个缘故,每次多线程在运行的时候,如果不希望数据是紊乱的,你就必须得加锁!(上面的线程代码上的Lock()换成RLock()也是一样的.)一加锁就跟没开线程是一样的.
所以,多线程在Python这里就是鸡肋.推荐使用多进程!
爬虫的提速上面,多进程也是不错的选择.虽然爬虫的网络IO的,但是在多进程上的效率也不输于多线程.