如何在 Python 中同时运行 2 个服务器? [英] How can I run 2 servers at once in Python?

查看:33
本文介绍了如何在 Python 中同时运行 2 个服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用线程模块在 Python 中一次运行 2 个服务器,但是要调用函数 run(),第一个服务器正在运行,但第二个服务器直到第一个服务器结束才运行.
这是源代码:

I need to run 2 servers at once in Python using the threading module, but to call the function run(), the first server is running, but the second server does not run until the end of the first server.
This is the source code:

import os
import sys
import threading

n_server = 0
n_server_lock = threading.Lock()

class ServersThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.start()
        self.join()

    def run(self):
        global n_server, n_server_lock

        if n_server == 0:
            n_server_lock.acquire()
            n_server += 1
            n_server_lock.release()

            print(['MainServer'])

            # This is the first server class    
            main_server = MainServer()
        elif n_server == 1:
            n_server_lock.acquire()
            n_server += 1
            n_server_lock.release()

            print (['DownloadServer'])

            # This is the second server class
            download_server = DownloadServer()

if __name__ == "__main__":
    servers = []

    for i in range(2):
        servers += [ServersThread()]

当我调用服务器类时,它会自动运行一个无限的while循环.
那么我怎样才能同时运行 2 个服务器呢?

When I call the server class, it automatically runs an infinite while loop.
So how can I run 2 servers at once?

非常感谢您的帮助 Fragsworth,我只是测试了新结构并完美运行.MainServer 和 DownloadServer 类继承自 threading.Thread 并在 run() 中运行无限循环.最后我按照你说的给服务器打电话.

Thank you very much for your help Fragsworth, I just test the new structure and working perfect. The MainServer and DownloadServer classes, inherit from threading.Thread and run the infinite loop inside run(). Finally I call the servers as you said.

推荐答案

您不希望 join() 在您的 __init__ 函数中.这会导致系统阻塞,直到每个线程完成.

You don't want to join() in your __init__ function. This is causing the system to block until each thread finishes.

我建议你重构你的程序,让你的主函数看起来更像下面这样:

I would recommend you restructure your program so your main function looks more like the following:

if name == "__main__":
    servers = [MainServer(), DownloadServer()]
    for s in servers:
        s.start()
    for s in servers:
        s.join()        

也就是说,为您的 MainServerDownloadServer 创建一个单独的线程类,然后让它们从主进程异步启动,然后加入.

That is, create a separate thread class for your MainServer and DownloadServer, then have them start asynchronously from the main process, and join afterwards.

这篇关于如何在 Python 中同时运行 2 个服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆