Python多线程

Python多线程

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

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

  • 它可以是抢占(中断)

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

启动一个新线程:

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

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

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

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

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

This would produce following result:

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

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

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/python

import threading
import time

exitFlag = 0

class 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.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.run()

while thread2.isAlive():
    if not thread1.isAlive():
        exitFlag = 1
    pass
print "Exiting Main Thread"

这将产生以下结果:

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

同步线程:

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

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

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

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

例子:

#!/usr/bin/python

import threading
import time

class 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 -= 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
Thread01: Thu Jan 22 16:04:38 2009
Thread01: Thu Jan 22 16:04:39 2009
Thread01: Thu Jan 22 16:04:40 2009
Thread02: Thu Jan 22 16:04:42 2009
Thread02: Thu Jan 22 16:04:44 2009
Thread02: Thu Jan 22 16:04:46 2009
Exiting Main Thread

多线程优先级队列:

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

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

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

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

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

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

Example:

#!/usr/bin/python

import Queue
import threading
import time

exitFlag = 0

class 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.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"

This would produce following result:

Starting Thread-2
Starting Thread-1
Starting Thread-3
Thread-2 processing One
Thread-1 processing Two
Thread-3 processing Three
Thread-2 processing Four
Thread-1 processing Five
Exiting Thread-3
Exiting Thread-2
Exiting Thread-1
Exiting Main Thread
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值