【发布时间】:2014-12-15 15:16:21
【问题描述】:
我试图多次运行一个线程并不断收到错误:
RuntimeError: threads can only be started once
我尝试阅读多线程并在我的代码中实现它,但没有任何运气。
这是我正在线程化的函数:
def receive(q):
host = ""
port = 13000
buf = 1024
addr = (host,port)
Sock = socket(AF_INET, SOCK_DGRAM)
Sock.bind(addr)
(data, addr) = Sock.recvfrom(buf)
q.put(data)
这是我要运行的代码:
q = Queue.Queue()
r = threading.Thread(target=receive, args=(q,))
while True:
r.start()
if q.get() == "stop":
print "Stopped"
break
print "Running program"
当stop 消息被发送时,程序应该跳出while 循环,但由于多线程,它不会运行。 while 循环应该不断打印出Running program,直到发送stop 消息。
队列用于从receive函数(即stop)接收变量data。
【问题讨论】:
-
你经常打电话给
r.start()?因为如果没有收到消息,您的q.get()将返回None(或者它可能是一个阻塞函数,不确定?)并且您的代码将尝试再次启动线程,即使第一个实例仍在运行。 -
@Lawrence 我试图通过在 while 循环结束时停止线程或创建另一个线程实例来克服这个问题,我不确定该怎么做。
-
threading模块没有名为thread的属性,因此您应该从threading.thread(target=receive, args=(q,))语句中获得AttributeError。 -
@martineau 打错了,用大写字母
thread和大写字母 T,Thread更正。这应该返回RuntimeError。
标签: python multithreading queue python-multithreading