Python 学习——多线程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 学习——多线程相关的知识,希望对你有一定的参考价值。
使用Threading模块创建线程:
threading模块有Thread类实现threading。Thread类提供的方法如下:
run():线程的入口点
start():调用run方法启动线程
join(time):等待线程结束
isAlive():检查一个线程是否仍旧在执行
getName():返回线程的名字
setName():设置一个线程的名字
要使用threading模块实现一个新线程,你得先如下做:
定义Thread类的一个子类。
重写__init__(self,[,args])方法以增加额外的参数
然后,重写run(self[,args])方法以实现线程启动后要做的事情
在你创建新的Thread子类以后,你可以创建它的一个实例,然后引用start()来开启一个新线程,它会依次调用call方法。
1. 一般线程:
例子:
#!/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"
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"
3. 多线程优先级队列:
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"
以上是关于Python 学习——多线程的主要内容,如果未能解决你的问题,请参考以下文章