Python多线程不适用于阻止I / O操作

问题描述

我已经按照“基本Python第二版”一书中的示例创建了一个Python脚本,该脚本使用线程来优化阻塞的I / O操作。代码如下:

import select
import socket
import time
from threading import Thread


def slow_systemcall():
    # Running the linux select system call,with 0.1 second timeout
    select.select([socket.socket()],[],0.1)

# First,run it linearly
start = time.time()

for _ in range(5):
    slow_systemcall()

end = time.time()
delta = end - start
print(f"Took {delta:.3f} seconds")

# Now,run it using threads
start = time.time()
threads = []
for _ in range(5):
    thread = Thread(target=slow_systemcall())
    thread.start()
    threads.append(thread)

for thread in threads:
    thread.join()

end = time.time()
delta = end - start
print(f"Took {delta:.3f} seconds")

我期望第一个打印的时间大约为“ Took 0.510秒”,第二个打印的时间大约为“ Took 0.108秒”,两者之间存在巨大差异。

但是,我得到的是 “花了0.520秒” 和 “花了0.519秒”

我在Mac上的Python 3.8和Linux上的Python 3.6.9中对此进行了测试。两者都产生相似的结果,其中多线程的使用似乎根本没有加快阻塞的I / O操作。

我做错了什么?

编辑:我注意到有些奇怪,并替换了这一行

thread = Thread(target=slow_systemcall())

与此行

thread = Thread(target=slow_systemcall)

它立即按预期工作。为什么会这样?

解决方法

要回答您的编辑,必须知道括号不是方法名称的一部分,而是用于调用它的。因此,添加它们会导致调用slow_systemcall方法本身并将其结果传递给目标参数。

,

您需要给新的Thread()函数对象。

通过添加调用Thread(target=slow_systemcall()),您可以调用该函数,然后传递结果,而不是传递函数本身。

Thread(target=slow_systemcall)传递了该函数,新线程调用了该函数。