[英]ThreadPoolExecutor Not Using Multiple Workers When Being Called Inside a Function
I'm trying to make a module that scans a given IP address and returns true or false for each port depending on it's current state.我正在尝试制作一个模块,该模块扫描给定的 IP 地址并根据其当前状态为每个端口返回 true 或 false。 It works fine when the context manager is called by itself but when it's called within a function it stops using all of it's allocated threads.
当上下文管理器被自己调用时它工作正常,但是当它在一个函数中被调用时它停止使用它分配的所有线程。 Here is my code:
这是我的代码:
import socket
import concurrent.futures
def _scan(ip, port):
scanner = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scanner.settimeout(1)
try:
scanner.connect((ip, port))
scanner.close()
return True
except:
return False
def portScan(ip, workers, portNum):
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
for port in range(portNum):
future = executor.submit(_scan, ip, port + 1)
print(future.result())
portScan("1.1.1.1", 100, 1000)
The problem is that you are waiting for each future to complete before submitting the next.问题是您在提交下一个之前等待每个未来完成。 You could use
map
instead.您可以改用
map
。 It will fan out the work to all of the threads and iterate the results in the same order as the parameters submitted.它会将工作分散到所有线程,并按照与提交参数相同的顺序迭代结果。
import socket
import concurrent.futures
def _scan(params):
ip, port = params
scanner = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scanner.settimeout(1)
try:
scanner.connect((ip, port))
scanner.close()
return True
except:
return False
def portScan(ip, workers, portNum):
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
for result in executor.map(_scan, ((ip, port) for port in range(portNum))):
print(result)
portScan("127.0.0.1", 5, 22)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.