python - 两段代码(关于 python GIL)有什么区别?

标签 python gil

片段代码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/

相关文章:

python - 如何控制 GTK 行间文本间距

python - 使用基于回调的 C 库时无法使用 Cython 释放 GIL

python - 包含 GIL 的简单 Python 函数

python - 对字符串列表执行算术运算

python - 暂时删除 python 模块

python - CvSize 不存在?

python - 有没有办法使用纯 python 为纯函数释放 GIL?

python - Python中的绿色线程和线程

python - 如何确定适当的检查间隔?

python - 在 python 项目中调用单元测试的通用约定?