片段代码1:
before = time()
urls = ['https://google.com'] * 5
for url in urls:
thread1 = Thread(target=get_content, args=(url,))
thread1.start()
thread1.join()
after = time()
print(after - before)
运行代码,结果为5.740652799606323
线程图是:
image link
片段代码2:
before = time()
thread1 = Thread(target=get_content, args=('https://google.com',))
thread2 = Thread(target=get_content, args=('https://google.com',))
thread3 = Thread(target=get_content, args=('https://google.com',))
thread4 = Thread(target=get_content, args=('https://google.com',))
thread5 = Thread(target=get_content, args=('https://google.com',))
thread1.start()
thread2.start()
thread3.start()
thread4.start()
thread5.start()
thread1.join()
thread2.join()
thread3.join()
thread4.join()
thread5.join()
after = time()
print(after - before)
运行代码,结果为:1.102950096130371
线程图是:
image link
我认为结果会类似。但最终的结果却并非如此。为什么?
谁能帮我解释一下吗?
最佳答案
在第一个代码段中,您实际上先等待每个线程首先完成,然后再启动另一个线程。您基本上是串行而不是并行运行它。
for url in urls:
thread1 = Thread(target=get_content, args=(url,))
thread1.start()
thread1.join()
在使用线程时,您可能想要做的是将每个线程保存在容器(列表)中,启动所有线程,然后等待所有线程完成。
ths = []
for url in urls:
thread1 = Thread(target=get_content, args=(url,))
thread1.start()
ths.append(thread1)
for t in ths:
t.join()
这段代码实际上完成了您第二个代码段所做的事情,只是用了一个循环。
关于python - 两段代码(关于 python GIL)有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51135638/