[英]How to run a thread more than once in python
I am trying to run a thread more than once and keep getting an error: 我试图多次运行一个线程并不断出现错误:
RuntimeError: threads can only be started once
I have tried reading up multithreading and implementing it in my code without any luck. 我尝试读取多线程并在我的代码中实现它,但是没有任何运气。
Here is the function I am threading: 这是我正在线程化的函数:
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)
Here is the code I want to run: 这是我要运行的代码:
q = Queue.Queue()
r = threading.Thread(target=receive, args=(q,))
while True:
r.start()
if q.get() == "stop":
print "Stopped"
break
print "Running program"
When the stop
message gets sent, the program should break out of the while loop, but it does not run due to multithreading. 发送
stop
消息后,该程序应退出while循环,但由于多线程而无法运行。 The while loop should constantly print out Running program
, until the stop
message is sent. while循环应不断打印出正在
Running program
,直到发送stop
消息为止。
The queue is used to receive the variable data
from the receive
function (which is the stop
). 该队列用于从
receive
函数(这是stop
)接收变量data
。
Here is a working example (for python 2.7). 这是一个工作示例(适用于python 2.7)。
The program has two modes of operation: 该程序具有两种操作模式:
Note how r.start()
and r.terminate()
are called outside of the while loop in client
. 注意如何在
client
的while循环之外调用r.start()
和r.terminate()
。 Also, receive
has a while True
loop. 另外,
receive
具有while True
循环。
import sys
import socket
from multiprocessing import Process, Queue
UDP_ADDR = ("", 13000)
def send(m):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(m, UDP_ADDR)
def receive(q):
buf = 1024
Sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Sock.bind(UDP_ADDR)
while True:
(data, addr) = Sock.recvfrom(buf)
q.put(data)
def client():
q = Queue()
r = Process(target = receive, args=(q,))
r.start()
print "client loop started"
while True:
m = q.get()
print "got:", m
if m == "stop":
break
print "loop ended"
r.terminate()
if __name__ == '__main__':
args = sys.argv
if len(args) > 1:
send(args[1])
else:
client()
I think the problem is once the thread is started, calling thread.start() again throws the error. 我认为问题在于线程启动后,再次调用thread.start()会引发错误。
Using a try block would might work as a simple fix: 使用try块可能会很简单:
while True: try: r.start() except Exception: #or except RunTimeError: pass if q.get() == "stop": print "Stopped" break print "Running program"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.