[英]How to hold a thread till MQTT message has arrived
In my app im sending a message via Paho MQTT and i have to wait for a response before sending new message. 在我的应用程序中,我通过Paho MQTT发送消息,我必须等待响应才能发送新消息。
eg: 例如:
while (!exit){
sendMessage(); //sends message via Paho MQTT
myMqttConnection.run() //starts a thread to wait for Response via Paho MQTT
//what to do to hold this thread till a message has arrived?
}
sendMessage() and myMqttConnection are 2 different topics in case that matters sendMessage()和myMqttConnection是两个不同的主题,以防万一
There's a few ways to tackle this, given the limited information that you have provided. 鉴于您提供的信息有限,有几种方法可以解决此问题。
If you have to spawn a thread in the myMqttConnection.run()
code, you need a way for your Threads to wait for each other. 如果必须在
myMqttConnection.run()
代码中生成线程,则需要一种让线程彼此等待的方法。
If you are happy with old-skool code, a shared guard object and a wait/notify mechanism would do it. 如果您对老式代码感到满意,则可以使用共享的保护对象和等待/通知机制。 The more modern way to do this is with something like a CyclicBarrier.
更现代的方法是使用CyclicBarrier之类的东西。
Otherwise, if you are spawning a thread in myMqttConnection.run()
, but then you wait for it to complete, you have to question why you are spawning a thread..? 否则,如果要在
myMqttConnection.run()
生成线程,但又等待其完成,则必须询问为什么要生成线程。 Why not just rename run()
to read()
and return the message from the read()
message. 为什么不只是将
run()
重命名为read()
并从read()
消息返回消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.