在 Python 中,您可以使用 Python 2.x 中的threading模块或 Python 3 中的_thread模块创建线程。我们将使用threading模块与之交互。
线程是一种操作系统进程,具有与正常进程不同的功能:
- 线程作为进程的子集存在
- 线程共享内存和资源
- 进程具有不同的地址空间(在内存中)
什么时候使用线程处理? 通常,当您希望功能与程序同时出现时。 如果创建服务器软件,则希望服务器不仅侦听一个连接,而且侦听许多连接。 简而言之,线程使程序能够一次执行多个任务。
Python 线程
让我们创建一个线程程序。 在此程序中,我们将启动 10 个线程,每个线程将输出其 ID。
import threading# Our thread classclass MyThread (threading.Thread):def __init__(self,x):self.__x = xthreading.Thread.__init__(self)def run (self):print str(self.__x)# Start 10 threads.for x in xrange(10):MyThread(x).start()
输出:
01...9
如果运行一次,线程不必停止。 线程可以是定时的,每x秒重复执行一次线程功能。
定时线程
在 Python 中,Timer类是Thread类的子类。 这意味着它的行为类似。我们可以使用计时器类来创建定时线程。计时器是通过.start()方法调用启动的,就像常规线程一样。 下面的程序创建一个线程,该线程在 5 秒钟后启动。
#!/usr/bin/env pythonfrom threading import *def hello():print "hello, world"# create threadt = Timer(10.0, hello)# start thread after 10 secondst.start()
使用线程
重复执行功能我们可以像这样无休止地执行线程:
#!/usr/bin/env pythonfrom threading import *import timedef handleClient1():while(True):print "Waiting for client 1..."time.sleep(5) # wait 5 secondsdef handleClient2():while(True):print "Waiting for client 2..."time.sleep(5) # wait 5 seconds# create threadst = Timer(5.0, handleClient1)t2 = Timer(3.0, handleClient2)# start threadst.start()t2.start()
