Python - 多线程

Python - 多线程 首页 / Python2入门教程 / Python - 多线程

运行多个线程类似于同时运行多个不同的程序,但具有以下优点-

  • 一个进程中的多个线程与主线程共享相同的数据空间,因此比起单进程,它们可以更轻松地共享信息或彼此通信。

  • 有时称为轻量级进程的线程,它们不需要太多的内存开销。

开始新线程

要生成另一个线程,您需要调用 thread 模块中可用的以下方法-

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

通过此方法调用,可以快速有效地在Linux和Windows中创建新线程。

方法调用立即返回,子线程启动,并使用传递的 args 列表调用函数。当函数返回时,线程终止。

在这里, args 是参数的元组;使用一个空的元组来调用函数而不传递任何参数。 kwargs 是关键字参数的可选词典。

#!/usr/bin/python

import thread
import time

# 为线程定义一个函数
def print_time( threadName, delay):
   count=0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# 创建两个线程如下
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: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

尽管它对于低级线程非常有效,但是与较新的线程模块相比, thread 模块非常有限。

Threading 模块

与上一节中讨论的线程模块相比,Python 2.4中包含的更新的线程模块为线程提供了更强大的高级支持。

threading 模块公开了 thread 模块的所有方法,并提供了一些其他方法-

  • threading.activeCount         -    返回活动的线程对象数。

  • threading.currentThread -   返回调用者线程控件中线程对象的数量。

  • threading.emumerrate        -   返回当前处于活动状态的所有线程对象的列表。

除了这些方法之外,线程模块还具有实现线程的 Thread 类。 Thread 类提供的方法如下-

  • run()                - run()方法是线程的入口点。

  • start()              - start()方法通过调用run方法来启动线程。

  • join([time])    - join()等待线程终止。

  • isAlive()          - isAlive()方法检查线程是否仍在执行。

  • getName()      - getName()方法返回线程的名称。

  • setName()      - setName()方法设置线程的名称。

模块创建线程

要使用线程模块实现新线程,您必须执行以下操作-

  • 定义 Thread 类的新子类。

  • 重写 __ init __(self [,args])方法以添加其他参数。

  • 然后,重写run(self [,args])方法以实现线程在启动时应执行的操作。

一旦创建了新的 Thread 子类,就可以创建它的,然后通过调用 start()来启动新线程,依次调用 run()方法。

#!/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

# 创建新线程
thread1=myThread(1, "Thread-1", 1)
thread2=myThread(2, "Thread-2", 2)

# 启动新线程
thread1.start()
thread2.start()

print "Exiting Main Thread"

执行以上代码后,将产生以下输出-

无涯教程网

Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2

同步线程

Python随附的线程模块包括易于实现的锁定机制,可让您同步线程。通过调用 Lock()方法创建一个新锁,该方法返回新锁。

新锁对象的 acquire(blocking)方法用于强制线程同步运行。可选的 blocking 参数使您可以控制线程是否等待获取锁。

如果 blocking 设置为0,则如果无法获取锁,则线程立即返回0值,如果获取锁,则线程返回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
      # 获取锁以同步线程
      threadLock.acquire()
      print_time(self.name, self.counter, 3)
      # 释放锁以释放下一个线程
      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=[]

# 创建新线程
thread1=myThread(1, "Thread-1", 1)
thread2=myThread(2, "Thread-2", 2)

# 启动新线程
thread1.start()
thread2.start()

# 将线程添加到线程列表
threads.append(thread1)
threads.append(thread2)

# 等待所有线程完成
for t in threads:
    t.join()
print "Exiting Main Thread"

执行以上代码后,将产生以下输出-

无涯教程网

Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread

优先级队列

队列模块允许您创建一个可以容纳特定数量项目的新队列对象。有以下方法来控制队列-

  • get()       - get()从队列中删除并返回一个项目。

  • put()       - 放置权将项目添加到队列中。

  • qsize()    - qsize()返回当前在队列中的项目数。

  • empty()  - 如果队列为空,则empty()返回True;否则,返回true。否则为False。

  • full()        - 如果队列已满,则full()返回True;否则,返回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

# 创建新线程
for tName in threadList:
   thread=myThread(threadID, tName, workQueue)
   thread.start()
   threads.append(thread)
   threadID += 1

# 填满队列
queueLock.acquire()
for word in nameList:
   workQueue.put(word)
queueLock.release()

# 等待队列清空
while not workQueue.empty():
   pass

# 通知线程是时候退出了
exitFlag=1

# 等待所有线程完成
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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

左耳听风 -〔陈皓〕

iOS开发高手课 -〔戴铭〕

Node.js开发实战 -〔杨浩〕

分布式技术原理与算法解析 -〔聂鹏程〕

设计模式之美 -〔王争〕

Serverless入门课 -〔蒲松洋(秦粤)〕

物联网开发实战 -〔郭朝斌〕

etcd实战课 -〔唐聪〕

计算机基础实战课 -〔彭东〕

好记忆不如烂笔头。留下您的足迹吧 :)