Python多线程

来源:互联网 发布:手机淘宝自定义链接 编辑:程序博客网 时间:2024/05/16 18:35

Python多线程

Python多线程例子教程:运行多个线程同时运行几个不同的程序类似,但具有以下优点.
运行多个线程同时运行几个不同的程序类似,但具有以下优点:进程内共享多线程与主线程相同的数据空间,如果他们是独立的进程,可以共享信息或互相沟通更容易.
  • 线程有时称为轻量级进程,他们并不需要多大的内存开销,他们关心的不是过程便宜.

一个线程都有一个开始,执行顺序,并得出结论。它有一个指令指针,保持它的上下文内正在运行的跟踪.

  • 它可以是抢占(中断)

  • 它可以暂时搁置(又称睡眠),而其他线程正在运行 - 这被称为产量yielding.

启动一个新线程:

如要产生另一个线程,你需要调用线程模块,可用下面的方法:

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

调用此方法实现了快速和有效的方式,在Linux和Windows中创建新的线程.

方法调用立即返回,并在子线程开始,并调用与传递agrs的列表函数。当函数返回时,线程终止.

这里的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

This would produce following result:

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

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

Threading 模块:

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

threading模块暴露所有的线程模块的方法,并提供一些额外的方法:

  • threading.activeCount():返回线程对象的数量处于活动状态的。.

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

  • threading.enumerate(): 返回一个所有当前处于活动状态线程对象的名单.

在另外的方法,线程模块实现线程Thread类。 Thread类提供的方法如下:

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

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

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

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

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

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

创建线程使用线程模块:

为了实现一个新的线程使用线程模块,你必须做到以下几点:

  • 定义一个新的Thread类的子类.

  • 覆盖 __init__(self [,args])方法来添加额外的参数.

  • 然后重写方法来实现的线程应该做的,什么时候开始 run(self [,args]) .

一旦你创建新的线程子类,你可以创建它的一个实例,然后启动一个新的线程调用的start()或run()方法.

例子:

#!/usr/bin/pythonimport threadingimport timeexitFlag = 0class myThread (threading.Thread):    def __init__(self, threadID, name, counter):        self.threadID = threadID        self.name = name        self.counter = counter        threading.Thread.__init__(self)    def run(self):        print "Starting " + self.name        print_time(self.name, self.counter, 5)        print "Exiting " + self.namedef 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 threadsthread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# Start new Threadsthread1.start()thread2.run()while thread2.isAlive():    if not thread1.isAlive():        exitFlag = 1    passprint "Exiting Main Thread"

这将产生以下结果:

Starting Thread-2Starting Thread-1Thread-1: Thu Jan 22 15:53:05 2009Thread-2: Thu Jan 22 15:53:06 2009Thread-1: Thu Jan 22 15:53:06 2009Thread-1: Thu Jan 22 15:53:07 2009Thread-2: Thu Jan 22 15:53:08 2009Thread-1: Thu Jan 22 15:53:08 2009Thread-1: Thu Jan 22 15:53:09 2009Exiting Thread-1Thread-2: Thu Jan 22 15:53:10 2009Thread-2: Thu Jan 22 15:53:12 2009Thread-2: Thu Jan 22 15:53:14 2009Exiting Thread-2Exiting Main Thread

同步线程:

与Python提供的线程模块,包括一个简单的实现锁定机制,将允许您同步线程。创建一个新的锁被调用的lock()方法,返回新锁.

获得(阻塞)新的锁定对象的方法将被用于迫使线程同步运行。阻塞的可选参数,使您能够控制是否线程将等待获得锁.

如果阻塞设置为0时,该线程将返回0值立即如果锁不能获得,1,如果锁被获得。如果阻塞设置为1时,该线程将被阻塞,等待被释放的锁.

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

例子:

#!/usr/bin/pythonimport threadingimport timeclass myThread (threading.Thread):    def __init__(self, threadID, name, counter):        self.threadID = threadID        self.name = name        self.counter = counter        threading.Thread.__init__(self)    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-2Thread01: Thu Jan 22 16:04:38 2009Thread01: Thu Jan 22 16:04:39 2009Thread01: Thu Jan 22 16:04:40 2009Thread02: Thu Jan 22 16:04:42 2009Thread02: Thu Jan 22 16:04:44 2009Thread02: Thu Jan 22 16:04:46 2009Exiting Main Thread

多线程优先级队列:

队列模块允许你创建一个新的队列对象,可容纳一个项目的具体数量。有以下方法来控制队列:

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

  • put(): put()把一个项目添加到队列中.

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

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

  • full(): full()返回True,如果队列已满,否则为false.

Example:

#!/usr/bin/pythonimport Queueimport threadingimport timeexitFlag = 0class myThread (threading.Thread):    def __init__(self, threadID, name, q):        self.threadID = threadID        self.name = name        self.q = q        threading.Thread.__init__(self)    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"

This would produce following result:

Starting Thread-2Starting Thread-1Starting Thread-3Thread-2 processing OneThread-1 processing TwoThread-3 processing ThreeThread-2 processing FourThread-1 processing FiveExiting Thread-3Exiting Thread-2Exiting Thread-1Exiting Main Thread
0 0
原创粉丝点击