首页 > python多线程加了join函数为什么会变慢?

python多线程加了join函数为什么会变慢?

这是在廖雪峰网站上的代码;

#coding:utf-8
import time, threading
def loop():
    print 'thread %s is running...' % threading.current_thread().name
    n = 0
    while n < 10:
        n = n + 1
        print 'thread %s >>> %s' % (threading.current_thread().name, n)
        time.sleep(0.1)
    print 'thread %s ended.' % threading.current_thread().name

print 'thread %s is running...' % threading.current_thread().name
t = threading.Thread(target=loop, name='LoopThread')
t.start()
#t.join()
print 'thread %s ended.' % threading.current_thread().name

我自己也写了一个多线程的小脚本:
https://github.com/hzlRises/hzlgithub/blob/master/RankingMonitoring/monitoring.py
在我写的这个里,为什么加了join函数以后,运行比不加join要慢很多
如果join函数的意思是等待上一个线程执行完再执行下一个线程,那写多线程的意义在哪里?


在加了.join()之后主线程(monitoring.py)会等待子线程结束之后才会退出。你的脚本里面记录时间记录的是主线程退出的时间。


t.join()的意思是等待t这个线程执行结束后,在往下顺序执行语句。如果不加的话,t还在执行中,然后就直接打印了print后面的内容,这个在你看来是运行结束了,但是其实t这个线程并没有结束。时间上是一样的。


为什么好多人联系我用多进程而不是多线程


因为不加join的话工作还没做完就直接退出了呀,join是阻塞等线程执行完毕。
不是快慢的问题,是对和错的问题。



尝试一下threadpool吧


join 阻塞执行调用join的这个进程,再执行主进程,也就是说,等t执行完,才会打印,如果你不加,那么t启动之后,会并行的往下执行,就是会打印出来,但是这个时候t进程并没有执行完毕。你肉眼看到以为是快,其实这样做是错误的。就正如pacoli说的一样。


join 函数是指等待线程执行结束再执行下面的代码,python 多线程一般受GIL影响,所以执行速度不会很快,建议楼主使用多进程,这样就会快一点!

【热门文章】
【热门文章】