我想通过MQTT连接发送数据,并在每次生成一组数据并将其发送时(在8个传感器中的一个上)启动一个新线程。之后,应该关闭该线程,因为我不再需要它。
atan
当我创建了几百个线程一段时间后运行代码时,出现此错误:
def send_on_sensor(q, delay, pub):
# I create a queue for each sensor
while q.empty is not True:
payload = json.dumps(q.get())
pub.publish(payload)
time.sleep(delay)
return # should the thread not close itself at return?
def send_dataset(secs=0):
qs = []
for i in range(8):
qs.append(queue.Queue())
for id in range(1000):
msg = {
"id": id,
}
# assign c accordingly
qs[c].put(msg)
# I have a MQTT publisher client for every q, which will be reused
for q in qs:
index = qs.index(q)
pub = publishers[index]
t = threading.Thread(target=send_on_sensor, args=(q, secs, pub))
t.daemon = True # I dont know if this actually helps here?
t.start()
time.sleep(secs)
while True:
send_dataset(output_interval)
time.sleep(output_interval * 200)
如何处理此错误?当我不再需要该线程时,如何精确地关闭该线程?拥有这么多线程正在运行甚至可能是一个糟糕的体系结构,我是否应该重写程序以对每个Traceback (most recent call last):
File "/Users//PycharmProjects//V3_multiTops/mt_GenPub.py", line 303, in <module>
send_dataset(X, y, output_interval)
File "/Users//PycharmProjects//V3_multiTops/mt_GenPub.py", line 127, in send_dataset
t.start()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 847, in start
_start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread
(队列)和相应的q
(发布者)使用固定线程?
如果是这样,我如何将新生成的数据移交给负责的线程?