您的位置:首页 > 编程语言 > Python开发

python2.7 threading 模块 一 Thread Timer Event

2016-08-26 17:03 477 查看
线程,多线程编程基本概念就不多讲了。这个就对常用的Object 作一个总结吧

1.Thread

Thread 可以理解为单独执行的某一项操作(activity),创建一个Thread有两种方式和Java一样

#coding:utf-8
import threading
class MyThread(threading.Thread): #继承父类threading.Thread
def __init__(self, num ):
threading.Thread.__init__(self)
self.num = num

#重写run方法
def run(self):
for i in range(self.num):
print 'I am %s.num:%s' % (self.getName(), i)

for i in range(3):
t = MyThread(3)
t.start()
t.join()
##########运行结果#########
>>> I am Thread-1.num:0
I am Thread-1.num:1
I am Thread-1.num:2
I am Thread-2.num:0
I am Thread-2.num:1
I am Thread-2.num:2
I am Thread-3.num:0
I am Thread-3.num:1
I am Thread-3.num:2


常用API

run(),通常需要重写,编写代码实现做需要的功能。
getName(),获得线程对象名称
setName(),设置线程对象名称
start(),启动线程
jion([timeout]),等待另一线程结束后再运行。
setDaemon(bool),设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False。
isDaemon(),判断线程是否随主线程一起结束。
isAlive(),检查线程是否在运行中

2.Timer
该对象就是实现某个操作在什么时候执行。内部实现可以理解为继承thread 然后再 run方法里面加一个time.sleep(num)简单的实现
def hello():
print "hello, world"

t = Timer(30.0, hello)
t.start()  # after 30 seconds, "hello, world" will be printed

3.Event  
事件机制是线程间通信机制的一种,Event对象实现了简单的线程通信机制,它提供了设置信号,清除信号,等待等用于实现线程间的通信。举个例子来说就如,跑步比赛的时候裁判是一个线程,各个运动员是是不同的线程,各个运动员(线程)都在等待裁判的枪声(event)才开始跑一样。
#coding:utf-8
#

import threading
import time
class MyThread(threading.Thread):

def __init__(self, name, event):
threading.Thread.__init__(self)
self.name = name
self.event = event

def run(self):
print "this is thread-%s waitting to start\n" % self.name
self.event.wait()
print "thread-%s is done \n" % self.name

def main():
event = threading.Event()
event.clear()
print "ready?\n"
for i in xrange(1,3):
thread = MyThread(i, event)
thread.start()
time.sleep(10)
print "GO\n"
event.set()

if __name__ == '__main__':
main()
ready?

this is thread-1 waitting to start

this is thread-2 waitting to start

GO

thread-1 is done

thread-2 is done


1.设置信号

使用Event的set()方法可以设置Event对象内部的信号标志为真。Event对象提供了isSet()方法来判断其内部信号标志的状态,当使用event对象的set()方法后,isSet()方法返回真.

2.清楚信号

使用Event对象的clear()方法可以清除Event对象内部的信号标志,即将其设为假,当使用Event的clear方法后,isSet()方法返回假

3.等待

Event对象wait的方法只有在内部信号为真的时候才会很快的执行并完成返回。当Event对象的内部信号标志位假时,则wait方法一直等待到其为真时才返回。

这部分就先总结 Thread,Timer,Event .
Lock,RLock,Condition,Semasphore 第二部分再写吧

用锤子,造房子~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python threading