Modeling a network in Python: instantiating objects in different threads and passing objects between threads in python

StackOverflow https://stackoverflow.com/questions/21663198

質問

I have a program in which I have modelled a network (i.e. it has switch, host, links, interfaces, etc. classes). I want each node in the network to operate in its own thread without waiting for another node to finish an operation. for example without multi-threading when I broadcast a packet from interfaces of a node, each packet (on each interface) has to wait for the previous packet to reach destination, get processed and terminated before it is transmitted. I am putting a part of my single-thread code down here so can anyone suggest a way I multi-thread my program?

main.py

from Simulation import Simulator

def main():

    newSim = Simulator()    #Simulator class holds the list of all nodes

    h1 = newSim.addNewHost()    #adds hosts
    h2 = newSim.addNewHost()

    s1 = newSim.addNewSwitch()    #adds switches
    s2 = newSim.addNewSwitch()

    c0 = newSim.addNewCont()    #adds a controller, which acts like a switch

    c0.connectTo(s1)    #creates NIC on each node and a link object which stores them
    c0.connectTo(s2)

    s1.connectTo(h1)
    s2.connectTo(h2)

    c0.initiateCtrl()    #initiates some operations on the controller

    # h1 has an interface (NIC) with 10.0.1.1
    # h2 has an interface (NIC) with 10.0.2.1

    h1.echo("Say hello to my little friend!!! BoooM!!!", "10.0.2.1")
    h2.echo("whats up!" , "10.0.1.1")  

if __name__ == '__main__':
    main()

now when I run this h2 waits until h1 sends its echo packet (and its ack) then it starts sending echo packet to h1. I suppose it is possible to send both echo packets simultaneously with multi-threading. but the examples online couldnt help me figure out how I should divide my program into threads, where to put locks and use queues

Thank you in advance.

役に立ちましたか?

解決

class SwitchCreator1(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.newSim = Simulator()
        self.s1 = self.newSim.addNewSwitch()

    def getSwitch1(self):
        return self.s1


class SwitchCreator2(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.newSim = Simulator()
        self.s2 = self.newSim.addNewSwitch()

    def getSwitch2(self):
        return self.s2

def main():

    threadList = []


    sc1 = SwitchCreator1()
    threadList.append(sc1)
    sc1.start()
    s1 = sc1.getSwitch1()

    sc2 = SwitchCreator2()
    threadList.append(sc2)
    sc2.start()
    s2 = sc2.getSwitch2()

    s1.connectTo(s2)

    s1.echo("Say hello to my little friend!!! BoooM!!!", s2)

    for t in threadList:
        t.join()

if __name__ == '__main__':
    main()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top