Python:多线程
我们先来看看【非多线程】的例子,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from time import ctime, sleep def music(): for i in range(3): print("【%s】Listening to music ..." % ctime()) sleep(1) def read(): for i in range(3): print("【%s】Reading on book ..." % ctime()) sleep(1) if __name__ == "__main__": # 没有多线程处理的情况下,代码是顺序执行的,前一个没有执行完是不会执行下一个的 music() read() print("------------------------") print("【%s】all over." % ctime()) |
它的执行结果如下:
1 2 3 4 5 6 7 8 9 10 11 |
D:\adamhuan_data\pycharm_data\python_Multi_Threads\venv\Scripts\python.exe D:/adamhuan_data/pycharm_data/python_Multi_Threads/multi_threads.py 【Sat Oct 9 11:11:47 2021】Listening to music ... 【Sat Oct 9 11:11:48 2021】Listening to music ... 【Sat Oct 9 11:11:49 2021】Listening to music ... 【Sat Oct 9 11:11:50 2021】Reading on book ... 【Sat Oct 9 11:11:51 2021】Reading on book ... 【Sat Oct 9 11:11:52 2021】Reading on book ... ------------------------ 【Sat Oct 9 11:11:53 2021】all over. Process finished with exit code 0 |
可以看到,在没有使用多线程的情况下,代码的调用是顺序的,在music()函数没有执行完之前,是不会执行read()函数的。
在Python中,有两个模块可以实现多线程:
- thread
- threading
其中,threading在thread的基础上,修复了一些缺陷,因此,直接使用threading就可以了。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
from time import ctime, sleep import threading def music(name): for i in range(3): print("【%s】Listening to music ...[%s]\n" % (ctime(),name)) sleep(1) def read(name): for i in range(5): print("【%s】Reading on book ...[%s]\n" % (ctime(),name)) sleep(4) if __name__ == "__main__": # 没有多线程处理的情况下,代码是顺序执行的,前一个没有执行完是不会执行下一个的 # music() # read() # print("------------------------") # print("【%s】all over." % ctime()) # 多线程处理代码 threads = [] thread1 = threading.Thread( target=music, args=('歌白帝',) ) threads.append(thread1) thread2 = threading.Thread( target=read, args=('道德情操论',) ) threads.append(thread2) for t in threads: t.setDaemon(True) t.start() for t in threads: t.join() print("") print("------------------------") print("【%s】all over." % ctime()) |
执行效果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
D:\adamhuan_data\pycharm_data\python_Multi_Threads\venv\Scripts\python.exe D:/adamhuan_data/pycharm_data/python_Multi_Threads/multi_threads.py 【Sat Oct 9 11:53:02 2021】Listening to music ...[歌白帝] 【Sat Oct 9 11:53:02 2021】Reading on book ...[道德情操论] 【Sat Oct 9 11:53:03 2021】Listening to music ...[歌白帝] 【Sat Oct 9 11:53:04 2021】Listening to music ...[歌白帝] 【Sat Oct 9 11:53:06 2021】Reading on book ...[道德情操论] 【Sat Oct 9 11:53:10 2021】Reading on book ...[道德情操论] 【Sat Oct 9 11:53:14 2021】Reading on book ...[道德情操论] 【Sat Oct 9 11:53:18 2021】Reading on book ...[道德情操论] ------------------------ 【Sat Oct 9 11:53:22 2021】all over. Process finished with exit code 0 |