简简单单小练习
1.线程的并发执行
import threading
import time
# 创建要执行的两个函数
def print_hello():
for _ in range(10):
print("hello")
time.sleep(1)
def print_world():
for _ in range(10):
print("world")
time.sleep(1)
# 创建线程对象 注意这里要写函数名,不能调用函数
thread_hello = threading.Thread(target=print_hello)
thread_world = threading.Thread(target=print_world)
# 开始进行线程
thread_hello.start()
thread_world.start()
# 等待线程结束
thread_hello.join()
thread_world.join()
总结:
- 准备一个函数。
- 使用 import threading 创建一个线程对象 t 。
- 使用 t.start() 来启动线程。
- 使用 t.join() 来等待线程的结束.
2.单线程与多线程的比较
下面是一个简单的爬虫案例,我们之后将用单线程与多线程分别操作进行比较
import requests
urls = [f"https://www.cnblogs.com/#p{page}" for page in range(1,51)]
def craw(url):
r = requests.get(url)
print(url,len(r.text))
craw(urls[0])
import threading
import time
import requests
urls = [f"https://www.cnblogs.com/#p{page}" for page in range(1,51)]
def craw(url):
r = requests.get(url)
print(url,len(r.text))
# 这里由于列表在函数上面作为全局变量,故没使用参数
def single_thread():
print("单线程函数开始")
# 遍历每一个网页
for url in urls:
craw(url)
print("single_thread end")
def multi_thread():
"""
多进程函数
这里是真正的多线程操作
之前的是通过休眠来模拟
:return:
"""
print("multi_thread begin")
# 创建空列表接受线程
threads = []
# 将创建的多个线程对象存入列表中
for url in urls:
threads.append(threading.Thread(target=craw,args=(url,)))
# 启动线程
for thread in threads:
thread.start()
# 等待线程结束
for thread in threads:
thread.join()
print("multi_thread end")
# 确定作为主程序执行
if __name__ == '__main__':
# 建立时间标记
start = time.time()
single_thread()



被折叠的 条评论
为什么被折叠?



