Python:如何创建服务器来监督线程池?

问题描述

我有一个线程池,可以同时处理一些任务。现在,我希望任务(此处为{{1})在退出之前先进行打印。

最初,我创建了一个锁,并将该锁传递给每个工作线程。如果线程要打印某些内容,则首先获取该锁,然后将其消息打印到stdout,然后释放该锁。

现在,我想拥有一个专用的事件驱动服务器线程来处理打印。如果线程想要打印某些内容,它只是通过Unix域套接字(multiply_by_2)将其消息发送到该服务器。我希望以此方式,可以减少每个线程的阻塞时间(无需等待锁),并且不需要在工作线程之间共享锁。服务器线程只会按顺序打印从客户端(即工作线程)获得的所有消息。

我使用Python的AF_UNIX模块(需要Python 3.7+)尝试了一段时间,但无法弄清楚。我该怎么办?

此清理后的模板为:

asyncio

一些额外要求:

  • 请勿创建# Python 3.7+ import asyncio import multiprocessing.dummy as mp # Threading wrapped using multiprocessing API. import os import socket import sys import threading import time server_address = './uds_socket' # UNIX domain socket def run_multiple_clients_until_complete(input_list): pool = mp.Pool(8) result_list = pool.map(multiply_by_2,input_list) return result_list def multiply_by_2(n): time.sleep(0.2) # Simulates some blocking call. message_str = "client: n = %d" % n # Todo send message_str.encode() to server return n * 2 # Server's callback when it gets a client connection # If you want to change it,please do.. def client_connected_cb( stream_reader: asyncio.StreamReader,stream_writer: asyncio.StreamWriter) -> None: message_str = reader.read().decode() print(message_str) def create_server_thread(): pass # Todo # Let the server finish handling all connections it got,then # stop the server and join the thread def stop_server_and_wait_thread(thread): pass # Todo def work(input_list): thread = create_server_thread() result_list = run_multiple_clients_until_complete(input_list) stop_server_and_wait_thread(thread) return result_list def main(): input_list = list(range(20)) result_list = work(input_list) print(result_list) if __name__ == "__main__": sys.exit(main()) asyncrun_multiple_clients_until_complete()multiply_by_2()
  • 使用main() UDP协议而不是SOCK_DGRAM TCP会更好,但这是不必要的。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)