运行几个线程和同时运行几个不同的程序类似,它有以下好处:
- 一个进程内的多个线程和主线程分享相同的数据空间,比分开不同的过程更容易分享信息或者彼此通信。
- 线程有时叫做轻量化过程,而且他们不要求更多的内存开支;它们比过程便宜。
一个线程的顺序是:启动,执行和停止。有一个指令指针跟踪线程正在运行的上下文在哪里。
- 它可以被抢占(中断)
- 它能暂时被挂起(也叫做休眠),而别的线程在运行--这也叫做yielding(让步)。
开始一个新线程:
要生成一个线程,需要调用在thread模块中方法如下:
thread.start_new_thread ( function, args[, kwargs] )
这种函数调用提供了创建新线程快速和有效的方法,适用于Windows和Linux。
方法立即返回,而子线程启动并调用函数,函数的参数为传递的args列表。当函数返回时,线程结束。
在这里,args是参数元组;调用函数而不传递任何参数使用空的元组。kwargs是可选的关键字参数字典。
例子:
#!/usr/bin/python
import thread import time # Define a function for the thread def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads as follows try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: pass
上述代码执行时,产生以下结果:
Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009
尽管对于低级别的线程,它是非常有效的,然而thread模块与较新的线程模块相比,其功能还是非常有限的。
Threading模块:
与前一节讨论的thread模块相比,从Python2.4开始包含的较新的threading模块,为线程提供了更多强大、高级的支持。
threading模块包含了thread模块中所有的方法,并提供一些其余的方法:
- threading.activeCount():返回激活的线程对象的数目
- theading.currentThread():返回调用者的线程控制中线程对象的数目
- threading.enumerate(): 返回当前活动的线程对象列表
除了方法,threading模块有Thread类实现threading。Thread类提供的方法如下:
- run():线程的入口点
- start():调用run方法启动线程
- join(time):等待线程结束
- isAlive():检查一个线程是否仍旧在执行
- getName():返回线程的名字
- setName():设置一个线程的名字
使用Threading模块创建线程:
要使用threading模块实现一个新线程,你得先如下做:
- 定义Thread类的一个子类。
- 重写__init__(self,[,args])方法以增加额外的参数
- 然后,重写run(self[,args])方法以实现线程启动后要做的事情
在你创建新的Thread子类以后,你可以创建它的一个实例,然后引用start()来开启一个新线程,它会依次调用call方法。
例子:
#!/usr/bin/python import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name print_time(self.name, self.counter, 5) print "Exiting " + self.name def print_time(threadName, delay, counter): while counter: if exitFlag: thread.exit() time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() print "Exiting Main Thread"
上述代码执行后,它会产出如下结果:
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2
同步线程:
Python提供的threading模块包括一个易于实现的锁定机制,以允许你同步线程。创建一个新锁通过调用Lock()实现,它也返回这个新锁。
新锁对象的accquire(blocking)方法,用来强制线程同步运行。可选的blocking参数使你能够控制线程是否请求锁。
如果blocking设置为0,线程在不能获取锁时立即返回0值;而blocking设置为1时,线程获取锁以后返回1值。如果blocking设置为1,线程将会阻塞,一直等到锁释放。
新锁对象的release()方法用来释放不再需要的锁。
例子:
#!/usr/bin/python import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name # Get lock to synchronize threads threadLock.acquire() print_time(self.name, self.counter, 3) # Free lock to release next thread threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 threadLock = threading.Lock() threads = [] # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread"
当上述代码执行后,它产生以下结果:
Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread
多线程优先级 队列:
Queue模块允许你创建一个新的队列对象,以盛放一定数量的项目。
控制Queue有以下方法:
- get():从队列移除一个项目并返回它
- put():把项目放入队列
- qsize():返回当前队列中项目的数量
- empty():如果队列为空,返回True,反之为False
- full():如果队列满了返回True,反之为False
例子:
#!/usr/bin/python import Queue import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print "Starting " + self.name process_data(self.name, self.q) print "Exiting " + self.name def process_data(threadName, q): while not exitFlag: queueLock.acquire() if not workQueue.empty(): data = q.get() queueLock.release() print "%s processing %s" % (threadName, data) else: queueLock.release() time.sleep(1) threadList = ["Thread-1", "Thread-2", "Thread-3"] nameList = ["One", "Two", "Three", "Four", "Five"] queueLock = threading.Lock() workQueue = Queue.Queue(10) threads = [] threadID = 1 # Create new threads for tName in threadList: thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread) threadID += 1 # Fill the queue queueLock.acquire() for word in nameList: workQueue.put(word) queueLock.release() # Wait for queue to empty while not workQueue.empty(): pass # Notify threads it's time to exit exitFlag = 1 # Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread"
当上述代码执行后,它产生以下结果:
Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread
Python多线程编程