如何在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)