设为首页 收藏本站
查看: 792|回复: 0

[经验分享] python threading 使用

[复制链接]

尚未签到

发表于 2017-4-24 12:05:11 | 显示全部楼层 |阅读模式
  上一篇 介绍了thread模块,今天来学习Python中另一个操作线程的模块:threading。threading通过对thread模块进行二次封装,提供了更方便的API来操作线程。今天内容比较多,闲话少说,现在就开始切入正题!
  threading.Thread
  Thread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;另一种是创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入。下面分别举例说明。先来看看通过继承threading.Thread类来创建线程的例子:
  #coding=gbk
import threading, time, random
count = 0
class Counter(threading.Thread):
def __init__(self, lock, threadName):
'''''@summary: 初始化对象。

@param lock: 琐对象。
@param threadName: 线程名称。
'''
super(Counter, self).__init__(name = threadName) #注意:一定要显式的调用父类的初始
化函数。
self.lock = lock

def run(self):
'''''@summary: 重写父类run方法,在线程启动后执行该方法内的代码。
'''
global count
self.lock.acquire()
for i in xrange(10000):
count = count + 1
self.lock.release()
lock = threading.Lock()
for i in range(5):
Counter(lock, "thread-" + str(i)).start()
time.sleep(2) #确保线程都执行完毕
print count
#coding=gbk
import threading, time, random
count = 0
class Counter(threading.Thread):
def __init__(self, lock, threadName):
'''@summary: 初始化对象。

@param lock: 琐对象。
@param threadName: 线程名称。
'''
super(Counter, self).__init__(name = threadName) #注意:一定要显式的调用父类的初始
化函数。
self.lock = lock

def run(self):
'''@summary: 重写父类run方法,在线程启动后执行该方法内的代码。
'''
global count
self.lock.acquire()
for i in xrange(10000):
count = count + 1
self.lock.release()
lock = threading.Lock()
for i in range(5):
Counter(lock, "thread-" + str(i)).start()
time.sleep(2)#确保线程都执行完毕
print count
  在代码中,我们创建了一个Counter类,它继承了threading.Thread。初始化函数接收两个参数,一个是琐对象,另一个是线程的名称。在Counter中,重写了从父类继承的run方法,run方法将一个全局变量逐一的增加10000。在接下来的代码中,创建了五个Counter对象,分别调用其start方法。最后打印结果。这里要说明一下run方法 和start方法: 它们都是从Thread继承而来的,run()方法将在线程开启后执行,可以把相关的逻辑写到run方法中(通常把run方法称为活动[Activity]。);start()方法用于启动线程。
  再看看另外一种创建线程的方法:
  import threading, time, random
count = 0
lock = threading.Lock()
def doAdd():
'''''@summary: 将全局变量count 逐一的增加10000。
'''
global count, lock
lock.acquire()
for i in xrange(10000):
count = count + 1
lock.release()
for i in range(5):
threading.Thread(target = doAdd, args = (), name = 'thread-' + str(i)).start()
time.sleep(2) #确保线程都执行完毕
print count
import threading, time, random
count = 0
lock = threading.Lock()
def doAdd():
'''@summary: 将全局变量count 逐一的增加10000。
'''
global count, lock
lock.acquire()
for i in xrange(10000):
count = count + 1
lock.release()
for i in range(5):
threading.Thread(target = doAdd, args = (), name = 'thread-' + str(i)).start()
time.sleep(2)#确保线程都执行完毕
print count
  在这段代码中,我们定义了方法doAdd,它将全局变量count 逐一的增加10000。然后创建了5个Thread对象,把函数对象doAdd 作为参数传给它的初始化函数,再调用Thread对象的start方法,线程启动后将执行doAdd函数。这里有必要介绍一下threading.Thread类的初始化函数原型:
def __init__(self, group=None, target=None, name=None, args=(), kwargs={})
  参数group是预留的,用于将来扩展;
  参数target是一个可调用对象(也称为活动[activity]),在线程启动后执行;
  参数name是线程的名字。默认值为“Thread-N“,N是一个数字。
  参数args和kwargs分别表示调用target时的参数列表和关键字参数。
  Thread类还定义了以下常用方法与属性:
  Thread.getName()
Thread.setName()
Thread.name
  用于获取和设置线程的名称。
  Thread.ident
  获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None。
  Thread.is_alive()
Thread.isAlive()
  判断线程是否是激活的(alive)。从调用start()方法启动线程,到run()方法执行完毕或遇到未处理异常而中断 这段时间内,线程是激活的。
  Thread.join([timeout])
  调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束。下面举个例子说明join()的使用:
  import threading, time
def doWaiting():
print 'start waiting:', time.strftime('%H:%M:%S')
time.sleep(3)
print 'stop waiting', time.strftime('%H:%M:%S')
thread1 = threading.Thread(target = doWaiting)
thread1.start()
time.sleep(1) #确保线程thread1已经启动
print 'start join'
thread1.join() #将一直堵塞,直到thread1运行结束。
print 'end join'
import threading, time
def doWaiting():
print 'start waiting:', time.strftime('%H:%M:%S')
time.sleep(3)
print 'stop waiting', time.strftime('%H:%M:%S')
thread1 = threading.Thread(target = doWaiting)
thread1.start()
time.sleep(1) #确保线程thread1已经启动
print 'start join'
thread1.join()#将一直堵塞,直到thread1运行结束。
print 'end join'
  threading.RLock和threading.Lock
  在threading模块中,定义两种类型的琐:threading.Lock和threading.RLock。它们之间有一点细微的区别,通过比较下面两段代码来说明:
  import threading
lock = threading.Lock() #Lock对象
lock.acquire()
lock.acquire() #产生了死琐。
lock.release()
lock.release()
import threading
lock = threading.Lock()#Lock对象
lock.acquire()
lock.acquire() #产生了死琐。
lock.release()
lock.release()
  import threading
rLock = threading.RLock() #RLock对象
rLock.acquire()
rLock.acquire() #在同一线程内,程序不会堵塞。
rLock.release()
rLock.release()
import threading
rLock = threading.RLock() #RLock对象
rLock.acquire()
rLock.acquire()#在同一线程内,程序不会堵塞。
rLock.release()
rLock.release()
  这两种琐的主要区别是:RLock允许在同一线程中被多次acquire。而Lock却不允许这种情况。注意:如果使用RLock,那么acquire和release必须成对出现,即调用了n次acquire,必须调用n次的release才能真正释放所占用的琐。
  threading.Condition
  可以把Condiftion理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。threadiong.Condition在内部维护一个琐对象(默认是RLock),可以在创建Condigtion对象的时候把琐对象作为参数传入。Condition也提供了acquire, release方法,其含义与琐的acquire, release方法一致,其实它只是简单的调用内部琐对象的对应的方法而已。Condition还提供了如下方法(特别要注意:这些方法只有在占用琐(acquire)之后才能调用,否则将会报RuntimeError异常。):
  Condition.wait([timeout]):
  wait方法释放内部所占用的琐,同时线程被挂起,直至接收到通知被唤醒或超时(如果提供了timeout参数的话)。当线程被唤醒并重新占有琐的时候,程序才会继续执行下去。
  Condition.notify():
  唤醒一个挂起的线程(如果存在挂起的线程)。注意:notify()方法不会释放所占用的琐。
  Condition.notify_all()
Condition.notifyAll()
  唤醒所有挂起的线程(如果存在挂起的线程)。注意:这些方法不会释放所占用的琐。
  现在写个捉迷藏的游戏来具体介绍threading.Condition的基本使用。假设这个游戏由两个人来玩,一个藏(Hider),一个找(Seeker)。游戏的规则如下:1. 游戏开始之后,Seeker先把自己眼睛蒙上,蒙上眼睛后,就通知Hider;2. Hider接收通知后开始找地方将自己藏起来,藏好之后,再通知Seeker可以找了; 3. Seeker接收到通知之后,就开始找Hider。Hider和Seeker都是独立的个体,在程序中用两个独立的线程来表示,在游戏过程中,两者之间的行为有一定的时序关系,我们通过Condition来控制这种时序关系。
  #---- Condition
#---- 捉迷藏的游戏
import threading, time
class Hider(threading.Thread):
def __init__(self, cond, name):
super(Hider, self).__init__()
self.cond = cond
self.name = name

def run(self):
time.sleep(1) #确保先运行Seeker中的方法

self.cond.acquire() #b
print self.name + ': 我已经把眼睛蒙上了'
self.cond.notify()
self.cond.wait() #c
#f
print self.name + ': 我找到你了 ~_~'
self.cond.notify()
self.cond.release()
#g
print self.name + ': 我赢了' #h

class Seeker(threading.Thread):
def __init__(self, cond, name):
super(Seeker, self).__init__()
self.cond = cond
self.name = name
def run(self):
self.cond.acquire()
self.cond.wait() #a #释放对琐的占用,同时线程挂起在这里,直到被notify并重新占
有琐。
#d
print self.name + ': 我已经藏好了,你快来找我吧'
self.cond.notify()
self.cond.wait() #e
#h
self.cond.release()
print self.name + ': 被你找到了,哎~~~'

cond = threading.Condition()
seeker = Seeker(cond, 'seeker')
hider = Hider(cond, 'hider')
seeker.start()
hider.start()
#---- Condition
#---- 捉迷藏的游戏
import threading, time
class Hider(threading.Thread):
def __init__(self, cond, name):
super(Hider, self).__init__()
self.cond = cond
self.name = name

def run(self):
time.sleep(1) #确保先运行Seeker中的方法

self.cond.acquire() #b
print self.name + ': 我已经把眼睛蒙上了'
self.cond.notify()
self.cond.wait() #c
#f
print self.name + ': 我找到你了 ~_~'
self.cond.notify()
self.cond.release()
#g
print self.name + ': 我赢了' #h

class Seeker(threading.Thread):
def __init__(self, cond, name):
super(Seeker, self).__init__()
self.cond = cond
self.name = name
def run(self):
self.cond.acquire()
self.cond.wait() #a #释放对琐的占用,同时线程挂起在这里,直到被notify并重新占
有琐。
#d
print self.name + ': 我已经藏好了,你快来找我吧'
self.cond.notify()
self.cond.wait() #e
#h
self.cond.release()
print self.name + ': 被你找到了,哎~~~'

cond = threading.Condition()
seeker = Seeker(cond, 'seeker')
hider = Hider(cond, 'hider')
seeker.start()
hider.start()
  threading.Event
  Event实现与Condition类似的功能,不过比Condition简单一点。它通过维护内部的标识符来实现线程间的同步问题。(threading.Event和.NET中的System.Threading.ManualResetEvent类实现同样的功能。)
  Event.wait([timeout])
  堵塞线程,直到Event对象内部标识位被设为True或超时(如果提供了参数timeout)。
  Event.set()
  将标识位设为Ture
  Event.clear()
  将标识伴设为False。
  Event.isSet()
  判断标识位是否为Ture。
  下面使用Event来实现捉迷藏的游戏(可能用Event来实现不是很形象)
  #---- Event
#---- 捉迷藏的游戏
import threading, time
class Hider(threading.Thread):
def __init__(self, cond, name):
super(Hider, self).__init__()
self.cond = cond
self.name = name

def run(self):
time.sleep(1) #确保先运行Seeker中的方法

print self.name + ': 我已经把眼睛蒙上了'

self.cond.set()

time.sleep(1)

self.cond.wait()
print self.name + ': 我找到你了 ~_~'

self.cond.set()

print self.name + ': 我赢了'

class Seeker(threading.Thread):
def __init__(self, cond, name):
super(Seeker, self).__init__()
self.cond = cond
self.name = name
def run(self):
self.cond.wait()

print self.name + ': 我已经藏好了,你快来找我吧'
self.cond.set()

time.sleep(1)
self.cond.wait()

print self.name + ': 被你找到了,哎~~~'

cond = threading.Event()
seeker = Seeker(cond, 'seeker')
hider = Hider(cond, 'hider')
seeker.start()
hider.start()
#---- Event
#---- 捉迷藏的游戏
import threading, time
class Hider(threading.Thread):
def __init__(self, cond, name):
super(Hider, self).__init__()
self.cond = cond
self.name = name

def run(self):
time.sleep(1) #确保先运行Seeker中的方法

print self.name + ': 我已经把眼睛蒙上了'

self.cond.set()

time.sleep(1)

self.cond.wait()
print self.name + ': 我找到你了 ~_~'

self.cond.set()

print self.name + ': 我赢了'

class Seeker(threading.Thread):
def __init__(self, cond, name):
super(Seeker, self).__init__()
self.cond = cond
self.name = name
def run(self):
self.cond.wait()

print self.name + ': 我已经藏好了,你快来找我吧'
self.cond.set()

time.sleep(1)
self.cond.wait()

print self.name + ': 被你找到了,哎~~~'

cond = threading.Event()
seeker = Seeker(cond, 'seeker')
hider = Hider(cond, 'hider')
seeker.start()
hider.start()
  threading.Timer
  threading.Timer是threading.Thread的子类,可以在指定时间间隔后执行某个操作。下面是Python手册上提供的一个例子:
  def hello():
print "hello, world"
t = Timer(3, hello)
t.start() # 3秒钟之后执行hello函数。
def hello():
print "hello, world"
t = Timer(3, hello)
t.start() # 3秒钟之后执行hello函数。
  threading模块中还有一些常用的方法没有介绍:
  threading.active_count()
threading.activeCount()
  获取当前活动的(alive)线程的个数。
  threading.current_thread()
threading.currentThread()
  获取当前的线程对象(Thread object)。
  threading.enumerate()
  获取当前所有活动线程的列表。
  threading.settrace(func)
  设置一个跟踪函数,用于在run()执行之前被调用。
  threading.setprofile(func)
  设置一个跟踪函数,用于在run()执行完毕之后调用。
  threading模块的内容很多,一篇文章很难写全,更多关于threading模块的信息,请查询Python手册 threading 模块。
  
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/JGood/archive/2009/06/29/4305604.aspx

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-368641-1-1.html 上篇帖子: 从零开始学Python 下篇帖子: Python基础:Python可变对象和不可变对象
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表