python thread模块_【Python@Thread】threading模块

theading模块的Thread类

属性:

name   线程名

ident   线程标识符

daemon   布尔值,标示是否为守护线程

方法:

__init__(target=None, name=None, *args=(), **kwargs={})

start()   开始执行线程

run()    定义线程功能的方法

join(timeout=None)  阻塞线程,等待被唤醒,好于忙等待

Thread类的使用主要有三种方法:

1.创建Thread实例,传给其一个参数

2.创建Thread实例,传给其一个可调用的类实例

3.派生Thread子类,创建子类实例

下面介绍这三种用法:

1.创建Thread实例,传给其一个参数

1 from threading importThread2 from time importctime, sleep3

4 loops = [4, 2]5

6

7 defloop(nloop, nsec):8 print('loops', nloop, 'starting at:', ctime())9 sleep(nsec)10 print('loop', nloop, 'end at:', ctime())11

12

13 defmain():14 print('starting at:', ctime())15 threads =[]16

17 for i inrange(len(loops)):18 t = Thread(target=loop, args=(i,loops[i]))19 threads.append(t)        ###保存类实例20

21 for i inrange(len(loops)):22 threads[i].start()        ###同时启动类实例23

24 for i inrange(len(loops)):25 threads[i].join()          ###保持主线程切出26

27 print('all done at:', ctime())28

29 if __name__ == '__main__':30 main()

运行结果:

starting at: Mon Dec 19 23:29:58 2016

loops 0 starting at: Mon Dec 19 23:29:58 2016

loops 1 starting at: Mon Dec 19 23:29:58 2016

loop 1 end at: Mon Dec 19 23:30:00 2016

loop 0 end at: Mon Dec 19 23:30:02 2016

all done at: Mon Dec 19 23:30:02 2016

方法1,传入函数创建类实例,不用人为设置锁,释放锁

方法二:传入可调用类创建类实例(用法感觉有点像装饰器)

1 from threading importThread2 from time importctime, sleep3

4 loops = [4, 2]5

6

7 classTFun():8 def __init__(self, name, func, args):9 self.name =name10 self.func =func11 self.args =args12

13 def __call__(self):14 return self.func(*self.args)15

16

17 defloop(nloop, nsec):18 print('loop', nloop, 'at:', ctime())19 sleep(nsec)20 print('loop', nloop, 'at:', ctime())21

22

23 defmain():24 print('starting at:', ctime())25 threads =[]26

27 for i inrange(len(loops)):28 t = Thread(target=TFun(loop.__name__, loop, (i,loops[i])))29 threads.append(t)30

31 for i inrange(len(loops)):32 threads[i].start()33

34 for i inrange(len(loops)):35 threads[i].join()36

37 print('all done at:', ctime())38

39 if __name__ == '__main__':40 main()

运行结果:

starting at: Mon Dec 19 23:46:31 2016

loop 0 at: Mon Dec 19 23:46:31 2016

loop 1 at: Mon Dec 19 23:46:31 2016

loop 1 at: Mon Dec 19 23:46:33 2016

loop 0 at: Mon Dec 19 23:46:35 2016

all done at: Mon Dec 19 23:46:35 2016

方法三:

派生Thread子类,创建子类实例

1 from threading importThread2 from time importctime, sleep3

4 loops = [4, 2]5

6

7 classmythread(Thread):8 def __init__(self, func, args, name=''):9 Thread.__init__(self)10 self.name =name11 self.func =func12 self.args =args13 self.name =name14

15 def run(self): #注意不是__call__(self)

16 self.func(*self.args)17

18

19 defloop(nloop, nsec):20 print('loop', nloop, 'at:', ctime())21 sleep(nsec)22 print('loop', nloop, 'end at:', ctime())23

24

25 defmain():26 print('starting at:', ctime())27 threads =[]28

29 for i inrange(len(loops)):30 t =mythread(loop,(i,loops[i]))31 threads.append(t)32

33 for i inrange(len(loops)):34 threads[i].start()35

36 for i inrange(len(loops)):37 threads[i].join()38

39 print('end at:', ctime())40

41 if __name__ == '__main__':42 main()

运行结果:

starting at: Tue Dec 20 00:06:00 2016

loop 0 at: Tue Dec 20 00:06:00 2016

loop 1 at: Tue Dec 20 00:06:00 2016

loop 1 end at: Tue Dec 20 00:06:02 2016

loop 0 end at: Tue Dec 20 00:06:04 2016

end at: Tue Dec 20 00:06:04 2016

方法二和方法三可以测试多个函数,其中方法三更加直观。但是方法1更加简单

参考资料:Python核心编程.第四章.Wesley Chun著

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值