参考:廖雪峰的官方网站
Python多线程
多任务可以由多进程完成,也可以由一个进程内的多线程完成。
我们前面提到了进程是由若干线程组成的,一个进程至少有一个线程。
由于线程是操作系统直接支持的执行单元,因此,高级语言通常都内置多线程的支持,Python也不例外,并且,Python的线程是真正的Posix Thread,而不是模拟出来的线程。
Python的标准库提供了两个模块:thread和threading,thread是低级模块,threading是高级模块,对thread进行了封装。绝大多数情况下,我们只需要使用threading这个高级模块。
启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行:
示例代码
# -*- coding: utf-8 -*-# @Time: 20.4.5 14:40# @FileName : testThread.py# @Software : PyCharmimport time, threading# 新线程执行的函数def calculate(num, totalList):print '子线程开启! thread (%s) is running...' % threading.current_thread().nametime.sleep(5)print '循环线程返回! thread (%s) ended.' % threading.current_thread().nametotalList.append(num * 10)if __name__ == '__main__':threads = []totalList = []results = []print '主线程开启! thread %s is running...' % threading.current_thread().namefor i in range(3, 6):cur_thread = threading.Thread(target=calculate, args=(i, totalList))threads.append(cur_thread)for thread in threads:thread.start()for thread in threads:thread.join()print 'totalList is:' + str(totalList)print '结束~~~ thread (%s) ended.' % threading.current_thread().name
输出:
主线程开启! thread MainThread is running…
子线程开启! thread (Thread-1) is running…
子线程开启! thread (Thread-2) is running…
子线程开启! thread (Thread-3) is running…
循环线程返回! thread (Thread-1) ended.
循环线程返回! thread (Thread-3) ended.
循环线程返回! thread (Thread-2) ended.
totalList is:[30, 50, 40]
结束~~~ thread (MainThread) ended.