Python中的网络建模:在不同线程中实例化对象并在Python中的线程之间传递对象
我有一个模拟网络的程序(即,它有交换机、主机、链接、接口等类)。我希望网络中的每个节点在自己的线程中运行,而不必等待另一个节点完成操作。例如,在没有多线程的情况下,当我从节点的接口广播一个数据包时,每个数据包(在每个接口上)必须等待前一个数据包到达目的地、得到处理并在传输之前终止。我把我的单线程代码的一部分放在这里,所以有人能建议一种方法我多线程我的程序吗 main.pyPython中的网络建模:在不同线程中实例化对象并在Python中的线程之间传递对象,python,multithreading,networking,simulate,Python,Multithreading,Networking,Simulate,我有一个模拟网络的程序(即,它有交换机、主机、链接、接口等类)。我希望网络中的每个节点在自己的线程中运行,而不必等待另一个节点完成操作。例如,在没有多线程的情况下,当我从节点的接口广播一个数据包时,每个数据包(在每个接口上)必须等待前一个数据包到达目的地、得到处理并在传输之前终止。我把我的单线程代码的一部分放在这里,所以有人能建议一种方法我多线程我的程序吗 main.py from Simulation import Simulator def main(): newSim = Si
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发送回显数据包。我认为可以使用多线程同时发送两个回显数据包。但是在线的例子不能帮助我弄清楚我应该如何将程序划分成线程,在哪里放置锁和使用队列
提前谢谢。请重新阅读您的帖子。该文件是真的“main.cpp”还是类似于main.py。看一下缩进,我想最后一行是错的。其余的还好吗?对不起,打字错误!我现在就编辑它。Ipython提供了易于使用的多处理工具。例如,结帐我不确定这是不是一个好方法,让我知道它是否是好的大师。非常感谢。
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()