Python多线程编程

来源:互联网 发布:app软件大全 编辑:程序博客网 时间:2024/04/30 12:32

Python多线程编程

运行几个线程和同时运行几个不同的程序类似,它有以下好处:
  •  一个进程内的多个线程和主线程分享相同的数据空间,比分开不同的过程更容易分享信息或者彼此通信。
  •  线程有时叫做轻量化过程,而且他们不要求更多的内存开支;它们比过程便宜。
一个线程的顺序是:启动,执行和停止。有一个指令指针跟踪线程正在运行的上下文在哪里。

  •  它可以被抢占(中断)
  •  它能暂时被挂起(也叫做休眠),而别的线程在运行--这也叫做yielding(让步)。

开始一个新线程:

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

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

这种函数调用提供了创建新线程快速和有效的方法,适用于Windows和Linux。
方法立即返回,而子线程启动并调用函数,函数的参数为传递的args列表。当函数返回时,线程结束。
在这里,args是参数元组;调用函数而不传递任何参数使用空的元组。kwargs是可选的关键字参数字典。

例子:

#!/usr/bin/python
[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import thread  
  2. import time  
  3.   
  4. # Define a function for the thread  
  5. def print_time( threadName, delay):  
  6.    count = 0  
  7.    while count < 5:  
  8.       time.sleep(delay)  
  9.       count += 1  
  10.       print "%s: %s" % ( threadName, time.ctime(time.time()) )  
  11.   
  12. # Create two threads as follows  
  13. try:  
  14.    thread.start_new_thread( print_time, ("Thread-1"2, ) )  
  15.    thread.start_new_thread( print_time, ("Thread-2"4, ) )  
  16. except:  
  17.    print "Error: unable to start thread"  
  18.   
  19.   
  20. while 1:  
  21.    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方法。


例子:
[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #!/usr/bin/python  
  2.   
  3. import threading  
  4. import time  
  5.   
  6. exitFlag = 0  
  7.   
  8. class myThread (threading.Thread):  
  9.     def __init__(self, threadID, name, counter):  
  10.         threading.Thread.__init__(self)  
  11.         self.threadID = threadID  
  12.         self.name = name  
  13.         self.counter = counter  
  14.     def run(self):  
  15.         print "Starting " + self.name  
  16.         print_time(self.name, self.counter, 5)  
  17.         print "Exiting " + self.name  
  18.   
  19. def print_time(threadName, delay, counter):  
  20.     while counter:  
  21.         if exitFlag:  
  22.             thread.exit()  
  23.         time.sleep(delay)  
  24.         print "%s: %s" % (threadName, time.ctime(time.time()))  
  25.         counter -= 1  
  26.   
  27. # Create new threads  
  28. thread1 = myThread(1"Thread-1"1)  
  29. thread2 = myThread(2"Thread-2"2)  
  30.   
  31. # Start new Threads  
  32. thread1.start()  
  33. thread2.start()  
  34.   
  35. 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()方法用来释放不再需要的锁。


例子:

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #!/usr/bin/python  
  2.   
  3. import threading  
  4. import time  
  5.   
  6. class myThread (threading.Thread):  
  7.     def __init__(self, threadID, name, counter):  
  8.         threading.Thread.__init__(self)  
  9.         self.threadID = threadID  
  10.         self.name = name  
  11.         self.counter = counter  
  12.     def run(self):  
  13.         print "Starting " + self.name  
  14.         # Get lock to synchronize threads  
  15.         threadLock.acquire()  
  16.         print_time(self.name, self.counter, 3)  
  17.         # Free lock to release next thread  
  18.         threadLock.release()  
  19.   
  20. def print_time(threadName, delay, counter):  
  21.     while counter:  
  22.         time.sleep(delay)  
  23.         print "%s: %s" % (threadName, time.ctime(time.time()))  
  24.         counter -= 1  
  25.   
  26. threadLock = threading.Lock()  
  27. threads = []  
  28.   
  29. # Create new threads  
  30. thread1 = myThread(1"Thread-1"1)  
  31. thread2 = myThread(2"Thread-2"2)  
  32.   
  33.   
  34. # Start new Threads  
  35. thread1.start()  
  36. thread2.start()  
  37.   
  38. # Add threads to thread list  
  39. threads.append(thread1)  
  40. threads.append(thread2)  
  41.   
  42. # Wait for all threads to complete  
  43. for t in threads:  
  44.     t.join()  
  45. 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
例子:
[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #!/usr/bin/python  
  2.   
  3. import Queue  
  4. import threading  
  5. import time  
  6.   
  7. exitFlag = 0  
  8.   
  9. class myThread (threading.Thread):  
  10.     def __init__(self, threadID, name, q):  
  11.         threading.Thread.__init__(self)  
  12.         self.threadID = threadID  
  13.         self.name = name  
  14.         self.q = q  
  15.     def run(self):  
  16.         print "Starting " + self.name  
  17.         process_data(self.name, self.q)  
  18.         print "Exiting " + self.name  
  19.   
  20. def process_data(threadName, q):  
  21.     while not exitFlag:  
  22.         queueLock.acquire()  
  23.         if not workQueue.empty():  
  24.             data = q.get()  
  25.             queueLock.release()  
  26.             print "%s processing %s" % (threadName, data)  
  27.         else:  
  28.             queueLock.release()  
  29.         time.sleep(1)  
  30.   
  31. threadList = ["Thread-1""Thread-2""Thread-3"]  
  32. nameList = ["One""Two""Three""Four""Five"]  
  33. queueLock = threading.Lock()  
  34. workQueue = Queue.Queue(10)  
  35. threads = []  
  36. threadID = 1  
  37.   
  38. # Create new threads  
  39. for tName in threadList:  
  40.     thread = myThread(threadID, tName, workQueue)  
  41.     thread.start()  
  42.     threads.append(thread)  
  43.     threadID += 1  
  44.   
  45. # Fill the queue  
  46. queueLock.acquire()  
  47. for word in nameList:  
  48.     workQueue.put(word)  
  49. queueLock.release()  
  50.   
  51. # Wait for queue to empty  
  52. while not workQueue.empty():  
  53.     pass  
  54.   
  55. # Notify threads it's time to exit  
  56. exitFlag = 1  
  57.   
  58. # Wait for all threads to complete  
  59. for t in threads:  
  60.     t.join()  
  61. 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
0 0