Understanding blocking and non-blocking code

So far, we have been working with blocking calls that processed MQTT-related network traffic and dispatched callbacks. Whenever we called the client.loop method in the previous examples, the method used the default values for the two optional arguments: 1 for timeout and 1 for max_packets. The method blocks for up to one second, that is, the value of the timeout argument, to handle incoming or outgoing data. The method runs with a synchronous execution, and therefore, the next line of code won't be executed until this method returns. We called the client.loop method in the main thread, and therefore, no other code can be executed in this thread while the client.loop method is blocking.

In our first example with Python code that created an MQTT client, we called the client.loop_forever method. This method blocks until the client calls the disconnect method. The method runs with a synchronous execution, and therefore, the next line of code won't be executed until the client calls the disconnect method. We also called the client.loop_forever in the main thread, and therefore, no other code can be executed in this thread while the client.loop_forever method is blocking.

One important difference between the loop method and the loop_forever method is that it is necessary to handle reconnections manually when we work with the loop method. The loop_forever method automatically handles reconnections to the MQTT server.

The paho-mqtt library provides us with a threaded client interface for the network loop that launches another thread that automatically calls the loop method. This way, it is possible to free up the main thread to run other code. The threaded interface is non-blocking and we don't have to worry about repeatedly calling the loop method. In addition, the threaded interface automatically handles reconnections to the MQTT server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.93.210