pythonthread模块_python标准库介绍——33 thread 模块详解

?==thread 模块==

(可选) ``thread`` 模块提为线程提供了一个低级 (low_level) 的接口, 如 [Example 3-6 #eg-3-6] 所示.

只有你在编译解释器时打开了线程支持才可以使用它. 如果没有特殊需要, 最好使用高级接口 ``threading`` 模块替代.

====Example 3-6. 使用 thread 模块====[eg-3-6]

```

File: thread-example-1.py

import thread

import time, random

def worker():

for i in range(50):

# pretend we're doing something that takes 10?00 ms

time.sleep(random.randint(10, 100) / 1000.0)

print thread.get_ident(), "-- task", i, "finished"

#

# try it out!

for i in range(2):

thread.start_new_thread(worker, ())

time.sleep(1)

print "goodbye!"

*B*311 -- task 0 finished

265 -- task 0 finished

265 -- task 1 finished

311 -- task 1 finished

...

265 -- task 17 finished

311 -- task 13 finished

265 -- task 18 finished

goodbye!*b*

```

注意当主程序退出的时候, 所有的线程也随着退出. 而 ``threading`` 模块不存在这个问题 . (该行为可改变)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值