- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsingle_multi_thread.py
More file actions
Latest commit
42 lines (33 loc) · 1.15 KB
/
Copy pathsingle_multi_thread.py
File metadata and controls
42 lines (33 loc) · 1.15 KB
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
importthreading
importtime
importrequests
urls= [f"https://www.cnblogs.com/#p{page}"forpageinrange(1, 50+1)]
defcraw(url):
r=requests.get(url)
print(url, r.text)
defsingle_thread():
print('single thread begin')
forurlinurls:
craw(url)
print('single thread end')
defmulti_thread():
print('muiti thread begin')
threads= []
forurlinurls:
threads.append(
threading.Thread(target=craw, args=(url,)) # 注意这里参数是一个元组,需要加逗号。否则识别为字符串
)
forthreadinthreads:
thread.start() # 启动线程
forthreadinthreads:
thread.join() # 默认情况下,主线程会创建多个子线程,且互不干涉。如果希望主线程等待子线程完成后,在执行后续操作。需要使用join,将其阻塞。
print('muiti thread end')
if__name__=="__main__":
start=time.time()
single_thread()
end=time.time()
print('single thread cost', end-start, 'seconds') # 耗时12.030196905136108 seconds
start=time.time()
multi_thread()
end=time.time()
print('multi thread cost', end-start, 'seconds') # 耗时0.47228384017944336 seconds