开发手册 欢迎您!
软件开发者资料库

Python - 多线程编程

Python多线程编程 - 从简单和简单的步骤学习Python,从基本到高级概念,包括Python语法面向对象语言,方法,元组,工具/实用程序,异常处理,套接字,GUI,扩展,XML编程。

运行多个线程类似于同时运行多个不同的程序,但具有以下优点 :

  • 多个线程在一个进程内与主线程共享相同的数据空间,因此可以比它们是单独的进程更容易地共享信息或相互通信.

  • 线程有时称为轻量级进程,它们不需要太多内存开销;它们比流程便宜.

线程有一个开头,一个执行序列和一个结论.它有一个指令指针,可以跟踪当前正在运行的上下文中的位置.

  • 它可以被抢占(中断)

  • 当其他线程正在运行时,它可以暂时被搁置(也称为休眠) - 这称为让步.

开始新线程

要生成另一个线程,需要在线程中调用以下方法模块 :

thread.start_new_thread(function,args [,kwargs])

此方法调用可以快速有效地在Linux和Windows中创建新线程.

方法调用立即返回,子线程启动并调用函数与传递的 args 列表.当函数返回时,线程终止.

这里, args 是一个参数元组;使用空元组来调用函数而不传递任何参数. kwargs 是关键字参数的可选字典.

示例

#!/usr/bin/pythonimport threadimport time# Define a function for the threaddef 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 followstry:   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 2009Thread-1: Thu Jan 22 15:42:19 2009Thread-2: Thu Jan 22 15:42:19 2009Thread-1: Thu Jan 22 15:42:21 2009Thread-2: Thu Jan 22 15:42:23 2009Thread-1: Thu Jan 22 15:42:23 2009Thread-1: Thu Jan 22 15:42:25 2009Thread-2: Thu Jan 22 15:42:27 2009Thread-2: Thu Jan 22 15:42:31 2009Thread-2: Thu Jan 22 15:42:35 2009

虽然它对低级别非常有效线程,但线程模块与较新的线程模块相比非常有限.

线程模块

Python 2.4中包含的较新的线程模块为线程提供了比上一节中讨论的线程模块更强大,更高级的支持.

线程模块公开了线程模块的所有方法,并提供了一些额外的方法 :

  • threading.activeCount() : 返回活动的线程对象的数量.

  • threading.currentThread() : 返回调用者线程控件中线程对象的数量.

  • threading.enumerate() : 返回当前活动的所有线程对象的列表.

除了方法之外,线程模块还有线程实现线程的类. Thread 类提供的方法如下 :

  • run( ) :  run()方法是线程的入口点.

  • start() :  start()方法通过调用run方法启动一个线程.

  • join([time]) :  join()等待线程终止.

  • isAlive() :  isAlive()方法检查线程是否仍在执行.

  • getName() :  getName()方法返回一个线程的名称.

  • setName() :  setName()方法设置线程的名称.

使用线程模块创建线程

要使用线程模块实现新线程,您必须执行以下操作 :

  • 定义 Thread 类的新子类.

  • 覆盖 __ init __(self [,args])添加其他参数的方法.

  • 然后,重写run(self [,args])方法以实现线程在启动时应该执行的操作.

创建新的 Thread 子类后,可以创建它的实例,然后启动新线程通过调用 start(),然后调用 run()方法.

示例

#!/usr/bin/pythonimport threadingimport timeexitFlag = 0class 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, 5, self.counter)      print "Exiting " + self.namedef print_time(threadName, counter, delay):   while counter:      if exitFlag:         threadName.exit()      time.sleep(delay)      print "%s: %s" % (threadName, time.ctime(time.time()))      counter -= 1# Create new threadsthread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# Start new Threadsthread1.start()thread2.start()print "Exiting Main Thread"

执行上述代码时,会产生以下结果 :

Starting Thread-1Starting Thread-2Exiting Main ThreadThread-1: Thu Mar 21 09:10:03 2013Thread-1: Thu Mar 21 09:10:04 2013Thread-2: Thu Mar 21 09:10:04 2013Thread-1: Thu Mar 21 09:10:05 2013Thread-1: Thu Mar 21 09:10:06 2013Thread-2: Thu Mar 21 09:10:06 2013Thread-1: Thu Mar 21 09:10:07 2013Exiting Thread-1Thread-2: Thu Mar 21 09:10:08 2013Thread-2: Thu Mar 21 09:10:10 2013Thread-2: Thu Mar 21 09:10:12 2013Exiting Thread-2

同步线程

Python提供的线程模块包含一个易于实现的锁定机制,允许您同步线程.通过调用 Lock()方法创建一个新锁,该方法返回新锁.

获取(阻塞)方法新锁对象用于强制线程同步运行.可选的 blocking 参数使您可以控制线程是否等待获取锁定.

如果阻止设置为0,则如果无法获取锁,则线程立即返回0值,如果获取了锁,则返回1.如果阻塞设置为1,则线程会阻塞并等待锁被释放.

新锁对象的 release()方法用于在不再需要时释放锁.

示例

#!/usr/bin/pythonimport threadingimport timeclass 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 -= 1threadLock = threading.Lock()threads = []# Create new threadsthread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# Start new Threadsthread1.start()thread2.start()# Add threads to thread listthreads.append(thread1)threads.append(thread2)# Wait for all threads to completefor t in threads:    t.join()print "Exiting Main Thread"

执行上述代码时,会产生以下结果 :

Starting Thread-1Starting Thread-2Thread-1: Thu Mar 21 09:11:28 2013Thread-1: Thu Mar 21 09:11:29 2013Thread-1: Thu Mar 21 09:11:30 2013Thread-2: Thu Mar 21 09:11:32 2013Thread-2: Thu Mar 21 09:11:34 2013Thread-2: Thu Mar 21 09:11:36 2013Exiting Main Thread

多线程Pri ority Queue

Queue 模块允许您创建一个可以容纳特定数量项目的新队列对象.有以下方法来控制队列和减号;

  • get() :  get()从队列中删除并返回一个项目.

  • put() :  put将项目添加到队列中.

  • qsize() :  qsize()返回当前队列中的项目数.

  • empty() : 如果队列为空,则empty()返回True;否则,错误.

  • full() : 如果队列已满,则full()返回True;否则,错误.

示例

#!/usr/bin/pythonimport Queueimport threadingimport timeexitFlag = 0class 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.namedef 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 threadsfor tName in threadList:   thread = myThread(threadID, tName, workQueue)   thread.start()   threads.append(thread)   threadID += 1# Fill the queuequeueLock.acquire()for word in nameList:   workQueue.put(word)queueLock.release()# Wait for queue to emptywhile not workQueue.empty():   pass# Notify threads it's time to exitexitFlag = 1# Wait for all threads to completefor t in threads:   t.join()print "Exiting Main Thread"

执行上面的代码时,它产生以下结果 :

Starting Thread-1Starting Thread-2Starting Thread-3Thread-1 processing OneThread-2 processing TwoThread-3 processing ThreeThread-1 processing FourThread-2 processing FiveExiting Thread-3Exiting Thread-1Exiting Thread-2Exiting Main Thread