如何在python中多次运行线程 [英] 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)
这是我要运行的代码:
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
消息为止.
When the stop
message gets sent, the program should break out of the while loop, but it does not run due to multithreading. The while loop should constantly print out Running program
, until the stop
message is sent.
队列用于从receive
函数(即stop
)接收变量data
.
The queue is used to receive the variable data
from the receive
function (which is the stop
).
推荐答案
这是一个有效的示例(适用于python 2.7).
Here is a working example (for python 2.7).
程序有两种操作模式:
- 不带任何参数,它将运行接收循环
- 带有参数的它发送一个数据报
请注意在client
的while循环之外如何调用r.start()
和r.terminate()
.
另外,receive
具有while True
循环.
Note how r.start()
and r.terminate()
are called outside of the while loop in client
.
Also, receive
has a while True
loop.
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()
这篇关于如何在python中多次运行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!