CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day01-15/code/Day13/multithread1.py
Views: 729
1
"""
2
使用多线程的情况 - 模拟多个下载任务
3
4
Version: 0.1
5
Author: 骆昊
6
Date: 2018-03-20
7
"""
8
9
from random import randint
10
from time import time, sleep
11
import atexit
12
import _thread
13
14
15
def download_task(filename):
16
print('开始下载%s...' % filename)
17
time_to_download = randint(5, 10)
18
print('剩余时间%d秒.' % time_to_download)
19
sleep(time_to_download)
20
print('%s下载完成!' % filename)
21
22
23
def shutdown_hook(start):
24
end = time()
25
print('总共耗费了%.3f秒.' % (end - start))
26
27
28
def main():
29
start = time()
30
# 将多个下载任务放到多个线程中执行
31
thread1 = _thread.start_new_thread(download_task, ('Python从入门到住院.pdf',))
32
thread2 = _thread.start_new_thread(download_task, ('Peking Hot.avi',))
33
# 注册关机钩子在程序执行结束前计算执行时间
34
atexit.register(shutdown_hook, start)
35
36
37
if __name__ == '__main__':
38
main()
39
40
# 执行这里的代码会引发致命错误(不要被这个词吓到) 因为主线程结束后下载线程再想执行就会出问题
41
# 需要说明一下 由于_thread模块属于比较底层的线程操作而且不支持守护线程的概念
42
# 在实际开发中会有诸多不便 因此我们推荐使用threading模块提供的高级操作进行多线程编程
43
44