Python中的多线程 - 阻止在后台运行
问题描述:
我最近一直在研究一个程序(正如你可能能够从我之前提出的问题中看到的那样),而且我在理解和实现多线程方面遇到了麻烦。Python中的多线程 - 阻止在后台运行
我按照教程(binary tides)设置了一个很好的UDP服务器。然而,我遇到的问题是,当我在一个新的线程上创建一个阻塞的UDP套接字时,我在我最初创建线程的主程序中的代码不起作用。下面是我的一些代码:
main.py:
from thread import*
import connections
start_new_thread(networkStart.startConnecton())
print 'This should print!'
networkStart.py:
def startConnecton():
userData.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
userData.s.bind((HOST, PORT))
except socket.error, msg:
print 'Bind failed. Error code: ' +str(msg[0]) + 'Message' +msg[1]
sys.exit()
print 'Socket bind complete'
userData.s.listen(10)
# Set the socket to listening mode, if there are more than 10 connections waiting reject the rest
print 'Socket now listening'
#Function for handling connections. Each new connection is handled on a separate thread
start_new_thread(connections.connectionListen())
connections.py:
def connectionListen():
while 1:
print 'waiting for connection'
#wait to accept a connection - blocking call
conn, addr = userData.s.accept()
userData.clients += 1
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments
start_new_thread(users.clientthread ,(conn, userData.clients))
我基本上只是想成为能够在新线程上调用startConnection函数后执行main.py中的任何代码(即在此实例中输出字符串) 。
我一直在为这个程序苦苦挣扎了一段时间,Python对我来说是新的,我发现它非常具有挑战性。我假设我必须在执行多线程的过程中发生一些错误,任何帮助都将不胜感激!
答
start_new_thread
接收函数和参数列表,但直接使用函数调用:start_new_thread(networkStart.startConnecton())
。
但是,我建议您使用具有更高抽象级别的threading
模块(the official documentation does so)。
import threading
import connections
threading.Thread(target=networkStart.startConnecton).start()
print 'This should print!'
+0
工作很好,谢谢 – 2013-03-14 16:51:51
这是一个完整的代码?你会得到什么错误?对'start_new_thread'的调用看起来无效。 – 2013-03-14 16:22:32