Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
hipersayan_x Avatar asked Dec 23 '09 18:12

hipersayan_x


People also ask

Can you run 2 servers at once?

You can create more than one server instance on your system. Each server instance has its own instance directory, and database and log directories. Multiply the memory and other system requirements for one server by the number of instances planned for the system.

Does Python run on the server side?

Python can be used as a server-side programming language. However it is not explicitly designed for this purpose. As a result, the amount of code necessary to allow Python to function well as a modern server-side language can be a burden.


1 Answers

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.

like image 148
Fragsworth Avatar answered Oct 18 '22 02:10

Fragsworth