2014-01-15 67 views
1

我想在python中创建3个线程,我正在使用python类线程库, 下面是在while循环中创建线程的正确方法吗?它可能会产生问题?在python中创建许多线程?

while (count <= 3): 
    try: 
     thread = CreateThread(count, args) 
     thread.start() 
    except: 
     logger.error("Error: unable to start thread ") 

任何其他正确的方法?

+0

看起来像你的问题是不是真的在这里定义。请过滤你的问题并告诉我们问题。 根据你对@Serdalis的评论回答,你有一个问题连接到你的路由器多次,而不是一个问题开始线程。请记住,大多数塑料路由器都有连接限制。 –

回答

3

虽然我们无法看到您的实际Thread类,但我会认为它是正确的,但在此代码中有一些可以改进的地方。

您需要保留对每个线程的引用,以便您可以在稍后停止/加入/等待它们。

所以,你的代码应该看起来更像是:

thread = [] 
for i in range(3): 
    try: 
     new_thread = CoreRouterThread(count, args) 
     new_thread.start() 
     # we append the thread here so we don't get any failed threads in the list. 
     thread.append(new_thread) 
    except: 
     logger.error("Error: unable to start thread ") 
+0

谢谢serdalis ...每个线程用于连接到路由器和获取数据...由于这个循环导致任何问题?..我正在通过对等错误 –

+0

得到连接重置这样的循环应该不会导致问题。你得到这个错误是因为[服务器不想和你说话](http://stackoverflow.com/questions/1434451/what-does-connection-reset-by-peer-mean)出于任何原因。您的网络编码或网络配置可能有问题。 – Serdalis