python - 如果循环内满足条件,如何在 while 循环中并行调用函数?

标签 python python-3.x sockets multiprocessing serversocket

我正在创建一个套接字,服务器每天在其中创建一个新的日志文件。午夜时分,需要备份前一天的日志。日志文件很大,压缩并上传到云端可能需要一些时间。我不希望服务器等到备份完成后才继续监听新的传入请求。我在下面的代码中根据 'if' 条件编写了伪代码,因为我不确定如何实现它。我猜我必须在这里使用多处理

while True:
    clientsocket, address = s.accept()
    enter_log("SUCCESS", "Established incoming connection from {}".format(address))

    if midnight:
        call_another_function_parallelly_for_backup_and_let_the_loop_continue_listening

最佳答案

while True:
    clientsocket, address = s.accept()
    enter_log("SUCCESS", "Established incoming connection from {}".format(address))

    if midnight:
        t = threading.Thread(target=your_func, args=(your_arg,))
        t.start()
        t.join()

def your_func(your_arg):
    try:
       your logic
    except Exception as e:
       print(e)

这将创建新线程,直到循环并且如果为 true...

关于python - 如果循环内满足条件,如何在 while 循环中并行调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550577/

相关文章:

python - 显示 3d ndarray 中的切片

python - SQLAlchemy 中的一对多关系

python - 有人能告诉我 python 中随机函数的内部工作原理吗?

c - 使用 fork() 的多客户端服务器

ios - 收到大量节时,应用程序的 UI 会卡住

python - Seaborn 中条形图和误差线的美观

python - 在 numpy 中矢量化 VLAD 计算

Python 3.7.0 没有名为 'PyQt5.QtWebEngineWidgets' 的模块

python 使用选择模型与套接字聊天

python - Pandas 如何过滤系列