1、threading 模块中的内容
- Thread: 一个可执行线程对象
- Lock: 原始的Lock对象 与thread模块中一样
- RLock: 允许单个线程多次请求的Lock
- Condition: 线程等待直到条件满足
- Event : 事件发生时,唤醒所有等待进程
- Semaphore:信号量,标识有限资源的个数
- Timer: 定时启动线程
- Barrier: 等待指定的所有的进程都来到
2、daemon threads 守护进程
如果你的主线程准备退出,并且你并不关心子线程是否完成,可以设置daemon,
‘thread.daemon = True’,表示该线程用于等待其子线程
3、Thread 类
类属:name: 线程名; ident:线程id; daemon:标识线程是否是守护线程
类方法:
“init(group=None,target=None,name=None,args=(),kwargs={},verbose=None,daemon=None”) 类构造函数,target是可执行函数
start(): 开始执行
run(): 定义线程功能,一般在子类中实现
join(timeout=None): 挂起直到调用其的线程结束,或等待timeout的时间
getName(): 返回线程名
setName(name): 设置线程名
isAlive/is_alive() : 线程是否还在运行
例子1:
import threading
from time import sleep, ctime
loops = [4,2]
def loop(nloop, nsec):
print ‘start loop‘,nloop
def main():
print ‘starting‘
threads=[]
nloops=range(len(loops))
for i in nloops:
t = threading.Thread(target=loop,args=(i,loops[i])
threads.append(t)
for i in nloops:
thread[i].start() # start threads
for i in nloops: # wait for all
threads[i].join() # threads to finish
if __name__ == ‘__main__‘:
main()
这里的target也可以是可调用的类实例
例子2:
import threading
form time import sleep, ctime
loops=[4,2]
class ThreadFunc(object):
def __init__(self,func,args,name=‘‘):
self.name=name
self.func=func
self.args=args
def __call__(self):
self.func(*self.args)
def loop(nloop,nsec):
print ‘start loop‘,nloop
def main():
print ‘starting‘
threads = []
nloops= range(len(loops))
for i in nloops: # create all threads
t = threading.Thread(
target=ThreadFunc(loop,(i,loops[i]),loop.__name__))
threads.append(t)
for i in nloops: #start all threads
threads.append(t)
for i in nloops: #wait for completion
threads[i].join()
print "all done"
if __name__=‘__main__‘:
main()
原文地址:http://blog.csdn.net/u010640235/article/details/46605331