有些小伙伴跟小编讨论了python中使用多线程原理的问题,就聊到了关于python多线程的弊端问题,这点可能在使用的过程中大家会能感觉到。而且之前讲过的GIL也是对python多线程的一种限制。那么,我们为什么还要用多线程呢?当然是多线程的优势已经掩盖了它本身不足之处,所以我们来加强一下学习python多线程的信心吧~
总结起来,使用多线程编程具有如下几个优点:
进程之间不能共享内存,但线程之间共享内存非常容易。
操作系统在创建进程时,需要为该进程重新分配系统资源,但创建线程的代价则小得多。因此,使用多线程来实现多任务并发执行比使用多进程的效率高。
Python 语言内置了多线程功能支持,而不是单纯地作为底层操作系统的调度方式,从而简化了 Python 的多线程编程。
threading模块
普通创建方式
import threading import time def run(n): print("task", n) time.sleep(1) print('2s') time.sleep(1) print('1s') time.sleep(1) print('0s') time.sleep(1) if __name__ == '__main__': t1 = threading.Thread(target=run, args=("t1",)) t2 = threading.Thread(target=run, args=("t2",)) t1.start() t2.start() ---------------------------------- > task t1 > task t2 > 2s > 2s > 1s > 1s > 0s > 0s
守护线程
我们看下面这个例子,这里使用setDaemon(True)把所有的子线程都变成了主线程的守护线程,因此当主进程结束后,子线程也会随之结束。所以当主线程结束后,整个程序就退出了。
import threading import time def run(n): print("task", n) time.sleep(1) #此时子线程停1s print('3') time.sleep(1) print('2') time.sleep(1) print('1') if __name__ == '__main__': t = threading.Thread(target=run, args=("t1",)) t.setDaemon(True) #把子进程设置为守护线程,必须在start()之前设置 t.start() print("end") ---------------------------------- > task t1 > end
我们可以发现,设置守护线程之后,当主线程结束时,子线程也将立即结束,不再执行。
python多线程实例代码:
1个线程时:
Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/2.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/3.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/4.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/5.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/6.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/7.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/8.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/9.html Done, Time cost: 8.182249069213867
2个线程时:
Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/2.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/3.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/4.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/5.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/6.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/7.html Current Thread Name Thread-2, Url: http://www.pythontab.com/html/pythonjichu/8.html Current Thread Name Thread-1, Url: http://www.pythontab.com/html/pythonjichu/9.html Done, Time cost: 4.0987958908081055