Python 多线程编程
运行多个线程类似于同时运行多个不同的程序,但有以下好处:
-
一个进程中的多个线程与主线程共享相同的数据空间,因此可以比单独的进程更容易地共享信息或相互通信。
-
线程有时称为轻量级进程,它们不需要太多内存开销;它们比工艺便宜。
一个线程有一个开始、一个执行顺序和一个结束。它有一个指令指针,用于跟踪它当前在其上下文中运行的位置。
-
它可以被抢占(中断)
-
它可以在其他线程运行时暂时搁置(也称为休眠) - 这称为屈服。
开始一个新线程
要生成另一个线程,你需要调用以下可用的方法 thread module:
thread.start_new_thread ( function, args[, kwargs] )
此方法调用支持在 Linux 和 Windows 中快速有效地创建新线程。
方法调用立即返回,子线程启动并使用传递的列表调用函数 args .当函数返回时,线程终止。
Here, 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穿线17 2009 Thread-1: Thu Jan 22 15穿线19 2009 Thread-2: Thu Jan 22 15穿线19 2009 Thread-1: Thu Jan 22 15穿线21 2009 Thread-2: Thu Jan 22 15穿线23 2009 Thread-1: Thu Jan 22 15穿线23 2009 Thread-1: Thu Jan 22 15穿线25 2009 Thread-2: Thu Jan 22 15穿线27 2009 Thread-2: Thu Jan 22 15穿线31 2009 Thread-2: Thu Jan 22 15穿线35 2009
虽然它对于低级线程非常有效,但是 thread 与较新的线程模块相比,模块非常有限。
The 穿线 Module
Python 2.4 中包含的较新的线程模块为线程提供了比上一节中讨论的线程模块更强大、更高级的支持。
The 穿线 模块暴露了所有的方法 thread 模块并提供了一些额外的方法:
-
threading.activeCount() :返回活跃的线程对象个数。
-
threading.currentThread() :返回调用者线程控制中线程对象的个数。
-
threading.enumerate() :返回当前处于活动状态的所有线程对象的列表。
除了方法之外,threading 模块还有 Thread 实现线程的类。提供的方法 Thread 类如下:
-
run() : run() 方法是线程的入口点。
-
start() : start() 方法通过调用run方法来启动一个线程。
-
加入([时间]) : join() 等待线程终止。
-
活着() : isAlive() 方法检查线程是否还在执行。
-
获取名称() : getName() 方法返回一个线程的名字。
-
设置名称() : setName() 方法设置线程的名称。
使用创建线程 穿线 Module
要使用 threading 模块实现新线程,你必须执行以下操作:
-
定义一个新的子类 Thread class.
-
覆盖 __init__(self [,args]) 添加其他参数的方法。
-
然后,重写 run(self [,args]) 方法来实现线程在启动时应该做什么。
一旦你创建了新的 Thread 子类,你可以创建它的一个实例,然后通过调用 start() ,这反过来又调用 run() method.
例子
#!/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, 5, self.counter) print "Exiting " + self.name def 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 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方法调用立即返回,子线程启动并使用传递的列表调用函数03 2013 Thread-1: Thu Mar 21 09方法调用立即返回,子线程启动并使用传递的列表调用函数04 2013 Thread-2: Thu Mar 21 09方法调用立即返回,子线程启动并使用传递的列表调用函数04 2013 Thread-1: Thu Mar 21 09方法调用立即返回,子线程启动并使用传递的列表调用函数05 2013 Thread-1: Thu Mar 21 09方法调用立即返回,子线程启动并使用传递的列表调用函数06 2013 Thread-2: Thu Mar 21 09方法调用立即返回,子线程启动并使用传递的列表调用函数06 2013 Thread-1: Thu Mar 21 09方法调用立即返回,子线程启动并使用传递的列表调用函数07 2013 Exiting Thread-1 Thread-2: Thu Mar 21 09方法调用立即返回,子线程启动并使用传递的列表调用函数08 2013 Thread-2: Thu Mar 21 09方法调用立即返回,子线程启动并使用传递的列表调用函数10 2013 Thread-2: Thu Mar 21 09方法调用立即返回,子线程启动并使用传递的列表调用函数12 2013 Exiting Thread-2
同步线程
Python 提供的线程模块包括一个易于实现的锁定机制,允许你同步线程。通过调用 Lock() 方法,它返回新的锁。
The 获取(阻塞) 新锁对象的方法用于强制线程同步运行。可选的 blocking 参数使你可以控制线程是否等待获取锁。
If blocking 如果设置为 0,则如果无法获取锁,则线程立即返回 0 值,如果获取了锁,则返回 1。如果blocking设置为1,线程阻塞并等待锁被释放。
The 发布() 新锁对象的方法用于在不再需要锁时释放锁。
例子
#!/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.当函数返回时,线程终止。28 2013 Thread-1: Thu Mar 21 09.当函数返回时,线程终止。29 2013 Thread-1: Thu Mar 21 09.当函数返回时,线程终止。30 2013 Thread-2: Thu Mar 21 09.当函数返回时,线程终止。32 2013 Thread-2: Thu Mar 21 09.当函数返回时,线程终止。34 2013 Thread-2: Thu Mar 21 09.当函数返回时,线程终止。36 2013 Exiting Main Thread
多线程优先队列
The Queue 模块允许你创建一个可以容纳特定数量的项目的新队列对象。队列控制有以下几种方法:
-
get() : get() 从队列中取出并返回一个项目。
-
put() : put 将项目添加到队列中。
-
qsize() : qsize() 返回当前在队列中的项目数。
-
empty() :如果队列为空,则empty()返回True;否则为假。
-
full() :full()如果队列满则返回True;否则为假。
例子
#!/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