Python多线程编程

浏览: 1163
  • threading.activeCo

python2.4前有个thread模块支持多线程编程,2.4后新增了threading模块,提供更高级别和更强大的线程支持.

  • threading.activeCount():返回激活的线程对象的数量
  • threading.currentThread():返回当前cpu执行的线程对象
  • threading.enumerate(): 返回当前激活的线程对象列表

除此之外,threading提供了很多和java中Thread类一样的方法:(注意这是都是实例方法)

  • run(): The run() method is the entry point for a thread.
  • start(): The start() method starts a thread by calling the run method.
  • join([time]): The join() waits for threads to terminate.
  • isAlive(): The isAlive() method checks whether a thread is still executing.
  • getName(): The getName() method returns the name of a thread.
  • setName(): The setName() method sets the name of a thread.

创建线程的方式有两种:

1)继承threading.Thread

a.创建一个threading.Thread的子类
b.覆盖__init__(self [,args])
c.重写run方法

#!/usr/bin/python 
#!coding=utf-8
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):
task()

def task(self):
'''线程要执行的任务'''
print 'starting ' + self.name
print 'exiting ' + self.name

#创建线程
thread1 = MyThread(1,'Thread-1', 1)
thread2 = MyThread(2,'Thread-2', 2)

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

#等待线程结束
thread1.join()
thread2.join()

print 'exiting main thread'

2)任务函数作为参数传递到Thread方法中

threading.Thread(target=task, args=()).start()
推荐 1
本文由 刘志军 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册