开发者

How can I run 2 servers at once in Python?

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()]

When I call the server class, it automatically runs an infinite while loop.

So how can I run 2 servers at once?


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.


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()        

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜