Python3多线程编程
运行多个线程类似于同时运行多个不同的程序,但具有以下优点:
-
进程中的多个线程与主线程共享相同的数据空间,因此与单独的进程相比,可以更轻松地共享信息或彼此通信。
-
线程有时被称为轻量级进程,它们不需要太多的内存开销。它们比流程便宜。
线程具有开始,执行序列和结论。它具有一个指令指针,可跟踪其上下文中当前正在运行的位置。
-
它可以被抢占(中断)。
-
可以在其他线程正在运行时将其暂时置于暂停状态(也称为休眠)-这称为yield。
有两种不同的线程:
- 内核线程
- 用户线程
内核线程是操作系统的一部分,而用户空间线程未在内核中实现。
有两个模块支持在Python3中使用线程:
- _thread
- 穿线
线程模块已被“弃用”了很长时间。鼓励用户改用线程模块。因此,在Python 3中,模块“线程”不再可用。但是,由于Python3中的向后兼容性,它已重命名为“ _thread”。
开始一个新线程
要生成另一个线程,你需要调用以下可用的方法 thread module:
_thread.start_new_thread ( function, args[, kwargs] )
通过此方法调用,可以快速有效地在Linux和Windows中创建新线程。
方法调用立即返回,子线程启动,并使用传递的列表调用函数 args 。当函数返回时,线程终止。
Here, args 是争论的元组;使用一个空的元组在不传递任何参数的情况下调用函数。 kwargs 是关键字参数的可选字典。
#!/usr/bin/python3 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: Fri Feb 19 09加入([时间])39 2016 Thread-2: Fri Feb 19 09加入([时间])41 2016 Thread-1: Fri Feb 19 09加入([时间])41 2016 Thread-1: Fri Feb 19 09加入([时间])43 2016 Thread-2: Fri Feb 19 09加入([时间])45 2016 Thread-1: Fri Feb 19 09加入([时间])45 2016 Thread-1: Fri Feb 19 09加入([时间])47 2016 Thread-2: Fri Feb 19 09加入([时间])49 2016 Thread-2: Fri Feb 19 09加入([时间])53 2016
程序陷入无限循环。你将必须按ctrl-c才能停止
尽管它对于低级线程非常有效,但是 thread 与较新的线程模块相比,该模块的功能非常有限。
线程模块
与上一节中讨论的线程模块相比,Python 2.4中包含的更新的线程模块为线程提供了更强大的高级支持。
The 穿线 模块公开了 thread 模块,并提供一些其他方法:
-
threading.activeCount() :返回活动的线程对象数。
-
threading.currentThread() :返回调用者线程控件中线程对象的数量。
-
threading.enumerate() :返回当前处于活动状态的所有线程对象的列表。
除了这些方法之外,线程模块还具有 Thread 实现线程的类。所提供的方法 Thread 班级如下:
-
run() :run()方法是线程的入口点。
-
start() :start()方法通过调用run方法来启动线程。
-
加入([时间]) :join()等待线程终止。
-
活着() :isAlive()方法检查线程是否仍在执行。
-
getName() :getName()方法返回线程的名称。
-
setName() :setName()方法设置线程的名称。
使用线程模块创建线程
要使用线程模块实现新线程,你必须执行以下操作:
-
定义一个新的子类 Thread class.
-
覆盖 __init __(self [,args]) 添加其他参数的方法。
-
然后,重写run(self [,args])方法以实现线程在启动时应执行的操作。
创建新的 Thread 子类,你可以创建它的实例,然后通过调用 start() ,这反过来称为 run() method.
#!/usr/bin/python3 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: 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() thread1.join() thread2.join() print ("Exiting Main Thread")
Result
当我们运行上述程序时,它将产生以下结果:
Starting Thread-1 Starting Thread-2 Thread-1: Fri Feb 19 10:00:21 2016 Thread-2: Fri Feb 19 10:00:22 2016 Thread-1: Fri Feb 19 10:00:22 2016 Thread-1: Fri Feb 19 10:00:23 2016 Thread-2: Fri Feb 19 10:00:24 2016 Thread-1: Fri Feb 19 10:00:24 2016 Thread-1: Fri Feb 19 10:00:25 2016 Exiting Thread-1 Thread-2: Fri Feb 19 10:00:26 2016 Thread-2: Fri Feb 19 10:00:28 2016 Thread-2: Fri Feb 19 10:00:30 2016 Exiting Thread-2 Exiting Main Thread
同步线程
Python随附的线程模块包括易于实现的锁定机制,可让你同步线程。通过调用 Lock() 方法,该方法返回新锁。
The 获取(阻止) 新锁对象的方法用于强制线程同步运行。可选的 blocking 参数使你可以控制线程是否等待获取锁。
If blocking 设置为0时,如果无法获取锁,则线程立即返回0值,如果获取锁,则线程立即返回1。如果将blocking设置为1,则线程将阻塞并等待释放锁。
The 释放() 新的锁对象的方法用于在不再需要时释放锁。
#!/usr/bin/python3 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: Fri Feb 19 10:04:14 2016 Thread-1: Fri Feb 19 10:04:15 2016 Thread-1: Fri Feb 19 10:04:16 2016 Thread-2: Fri Feb 19 10:04:18 2016 Thread-2: Fri Feb 19 10:04:20 2016 Thread-2: Fri Feb 19 10:04:22 2016 Exiting Main Thread
多线程优先级队列
The Queue 模块允许你创建一个可以容纳特定数量项目的新队列对象。有以下几种控制队列的方法:
-
get() :get()从队列中删除并返回一个项目。
-
put() :推杆将项目添加到队列中。
-
qsize() :qsize()返回队列中当前存在的项目数。
-
empty() :如果队列为空,则Empty()返回True;否则,返回true。否则为False。
-
full() :如果队列已满,则full()返回True;否则,返回true。否则为False。
#!/usr/bin/python3 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