【问题标题】:How can I divide work read from a file to threads?如何将工作从文件读取到线程?
【发布时间】:2019-04-30 22:16:22
【问题描述】:

我有一个主机列表和一个端口列表。 我想运行 X 线程,每次都会抓取一个主机并尝试连接到这些端口。 我得到了连接部分,我的问题是如何穿线。 当我做一些研究时,我对线程、多进程和异步感到非常困惑。 什么是最优化和/或最简单的库?

现在我的伪代码没有线程代码是:

def getHosts():
    hosts = open("hostList.txt").read().splitlines()
    return hosts
def getPorts():
    ports = open("portList.txt").read().splitlines()

hosts = getHosts()
ports = getPorts()
for host in hosts
    for port in ports
        ---the connection code---

我认为我的一般想法是取列表的长度,将其除以线程数并创建一个线程,该线程将从 thread_number*result_of_divide 运行直到 (thread_number+1)*result_of_divide。

【问题讨论】:

  • 请注意,由于GIL,线程和异步不允许并行运行代码。因此,对于并行执行,您将需要多处理(或其他编程语言:))
  • @YevhenKuzmovych 感谢您的帮助,GIL 非常有趣,我希望我会使用 ThreadPoolExecutor 来实现它。

标签: python multithreading


【解决方案1】:

ThreadPoolExecutor.

import concurrent.futures

MAX_THREAD_COUNT = 10


def read_text_file(filename):
    with open(filename, "r") as f:
        return f.read().splitlines()


def check_port(host, port):
    pass


hosts = read_text_file("hostList.txt")
ports = read_text_file("portList.txt")


with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREAD_COUNT) as executor:
    results = {}
    for host in hosts:
        for port in ports:
            results[executor.submit(check_port, host, port)] = "{}:{}".format(host, port)

for result in concurrent.futures.as_completed(results):
    host_and_port = results[result]
    try:
        returned_data = result.result()
    except Exception as e:
        print("\"{}\" exception have been caused while checking {}".format(e, host_and_port))
    else:
        print("Checking of {} returned {}".format(host_and_port, returned_data))

P.S. 代码可能不是 100% 正确的,我还没有“实际”检查它。

【讨论】:

  • 这太棒了!我复制了它,玩了它,然后删除并从“头”开始写,它工作得很好!
  • @AviShabat,希望您了解它的工作原理,而不仅仅是复制;)
  • 这就是为什么我说我复制、播放和删除。我复制来看看它是如何工作的,玩来检查我能用它做什么,然后写了一个全新的脚本。我有错误并修复了它们,这有助于我更好地理解和记住。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 2016-12-21
  • 1970-01-01
  • 2018-01-30
  • 2011-11-18
  • 1970-01-01
相关资源
最近更新 更多