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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
?==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`` 模块不存在这个问题 . (该行为可改变)

  

posted @   淋哥  阅读(896)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示