Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中控制非常大的循环中的最大线程数_Python_Multithreading_Python Multithreading - Fatal编程技术网

如何在Python中控制非常大的循环中的最大线程数

如何在Python中控制非常大的循环中的最大线程数,python,multithreading,python-multithreading,Python,Multithreading,Python Multithreading,我尝试使用多线程来迭代服务器列表,并为每个服务器发送网络请求以获取服务器状态 for s in all_servers: thread = threading.Thread(target=s.get_server_status) thread.start() threads.append(thread) for thread in threads: thread.join() 但是,生产中可能有2000多台服务器,所以我担心2000个线程是坏的 如果是

我尝试使用多线程来迭代服务器列表,并为每个服务器发送网络请求以获取服务器状态

for s in all_servers:

    thread = threading.Thread(target=s.get_server_status)

    thread.start()

    threads.append(thread)

for thread in threads:

    thread.join()
但是,生产中可能有2000多台服务器,所以我担心2000个线程是坏的

如果是,我如何控制它生成的最大线程数?

您可以使用

在本例中,只有4个并发进程将运行。

您可以使用


在本例中,只有4个并发进程将运行。

这将导致无法pickle:attribute lookup builtin.function失败错误抱歉!我的错!pool.map在使用lambda时出现此错误。我已经更新了一个命名方法的答案。不,仍然是同样的问题@MuhammadTahir@Chrim您正在以交互模式尝试代码吗<代码>多处理.Pool.map在交互模式下不工作。您需要将它放在
.py
文件中,然后像
python myfile.py
一样运行来测试它。它在python2和python3中对我都有效。@Tahir-Hmmm,不知道为什么,我稍后会看。我没有在交互模式下运行它。这会导致无法pickle:属性查找内置。函数失败错误抱歉!我的错!pool.map在使用lambda时出现此错误。我已经更新了一个命名方法的答案。不,仍然是同样的问题@MuhammadTahir@Chrim您正在以交互模式尝试代码吗<代码>多处理.Pool.map在交互模式下不工作。您需要将它放在
.py
文件中,然后像
python myfile.py
一样运行来测试它。它在python2和python3中对我都有效。@Tahir-Hmmm,不知道为什么,我稍后会看。我没有在交互模式下运行它
def get_server_status(s):
    return s.get_server_status()
pool = Pool(processes=4)
pool.map(get_server_status, all_servers)