在 Python 中建模网络:在不同线程中实例化对象并在 python 中的线程之间传递对象



我有一个程序,其中我对网络进行了建模(即它有交换机,主机,链路,接口等类)。我希望网络中的每个节点都在自己的线程中运行,而无需等待另一个节点完成操作。例如,当我从节点的接口广播数据包时,如果没有多线程,每个数据包(在每个接口上)必须等待前一个数据包到达目的地,在传输之前得到处理和终止。我把我的单线程代码的一部分放在这里,所以任何人都可以建议我的多线程程序的方法吗?

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

现在,当我运行此 h2 时,它会等到 h1 发送其回声数据包(及其 ack),然后它开始向 h1 发送回声数据包。我想可以通过多线程同时发送两个回显数据包。但是网上的例子无法帮助我弄清楚如何将我的程序划分为线程,在哪里放置锁和使用队列

提前谢谢你。

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

最新更新