Python线程– Python多线程
Python线程模块用于在python程序中实现多线程。
在本课中,我们将研究Thread和pythonthreading
模块的不同功能。
Python多处理是我们前一段时间研究的类似模块之一。
什么是线程?
在计算机科学中,线程被定义为计划由操作系统完成的最小工作单元。
有关线程的几点注意事项:
线程存在于进程内部。
一个进程中可以存在多个线程。
同一进程中的线程共享父进程的状态和内存。
Python线程
让我们通过一个简单的好例子介绍pythonthreading
模块:
import time from threading import Thread def sleepMe(i): print("Thread %i going to sleep for 5 seconds." % i) time.sleep(5) print("Thread %i is awake now." % i) for i in range(10): th = Thread(target=sleepMe, args=(i, )) th.start()
当我们运行此脚本时,将输出以下内容:
当您运行此程序时,输出可能会有所不同,因为并行线程的寿命没有任何定义的顺序。
Python线程功能
我们将重用用threading模块编写的最后一个简单程序,并构建该程序以显示不同的线程功能。
threading.active_count()
该函数返回当前正在执行的线程数。
让我们修改最后一个脚本的sleepMe(...)
函数。
我们的新脚本将如下所示:
import time import threading from threading import Thread def sleepMe(i): print("Thread %i going to sleep for 5 seconds." % i) time.sleep(5) print("Thread %i is awake now." % i) for i in range(10): th = Thread(target=sleepMe, args=(i, )) th.start() print("Current Thread count: %i." % threading.active_count())
这次,我们将有一个新的输出,显示有多少线程处于活动状态。
这是输出:
请注意,在全部10个线程启动之后,活动线程计数不是10,而是11。
这是因为它还对生成的其他10个线程中的主线程进行计数。
threading.current_thread()
该函数返回正在执行的当前线程。
使用此方法,我们可以对获得的线程执行特定的操作。
让我们修改脚本以立即使用此方法:
import time import threading from threading import Thread def sleepMe(i): print("Thread %s going to sleep for 5 seconds." % threading.current_thread()) time.sleep(5) print("Thread %s is awake now.\n" % threading.current_thread()) #Creating only four threads for now for i in range(4): th = Thread(target=sleepMe, args=(i, )) th.start()
上面脚本的输出将是:
threading.main_thread()
该函数返回该程序的主线程。
可以从该线程中产生更多线程。
让我们看一下这个脚本:
import threading print(threading.main_thread())
值得注意的是main_thread()
函数仅在Python 3中引入。
因此请注意,仅在使用Python 3+版本时才使用此函数。
threading.enumerate()
此函数返回所有活动线程的列表。
这个用起来很简单。
让我们编写一个脚本来使用它:
import threading for thread in threading.enumerate(): print("Thread name is %s." % thread.getName())
执行此脚本时只有主线程,因此只有输出。
threading.Timer()
这个threading
模块的功能用于创建一个新的Thread,并让它知道它应该只在指定的时间之后启动。
一旦启动,它应该调用指定的函数。
让我们用一个例子来研究它:
import threading def delayed(): print("I am printed after 5 seconds!") thread = threading.Timer(3, delayed) thread.start()