Search code examples
pythonoopserverconstructorinstance

How to count the Index of an instance?


I want to start multiple servers like this:

Server 1
Server 2
Server 3

I have already written a code:

class Server:
     def __init__(self, index):
          self.index = index

My main is looking like this:

server1 = Server(1)
server1.run()

So my question is as you can read in the captio: How can I global count the Index of different instances (Servers) dynamically?


Solution

  • Store the total instance count in a class variable.

    class Server:
        instances = 0   
        def __init__(self):
             Server.instances += 1
             self.index = Server.instances
    

    Solving this problem across multiple instances requires more work. You must use a file to hold the counter, and you must ensure that two processes don't fight over who gets to open the file next. This should work on Linux:

    import fcntl
    class Server:
        CNTR = 'mycounter.txt'
        def __init__(self):
            if not os.path.exists(CNTR):
                open(CNTR,'w').write('0')
            fctl.lock( f, fcntl.LOCK_EX )
            n = int(open(CNTR).read()) + 1
            open(CNTR,'w').write(str(n))
            fctl.lock( f, fcntl.LOCK_UN )
    
            self.index = n