Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best practice when using with go routines #4

Open
brutella opened this issue Apr 26, 2023 · 4 comments
Open

Best practice when using with go routines #4

brutella opened this issue Apr 26, 2023 · 4 comments

Comments

@brutella
Copy link
Contributor

My MQTT client is using this library to abstract the communication with a broker. At first this library looks pretty straight forward to use, but I do find it hard to use with go routines.

Why go routines?
Some parts of the MQTT protocol requires you to read and write simultaneously. For example once you are connected to a broker, you have to send a Ping message after n seconds to keep the connection alive. But also when you're subscribed to a topic, you have to keep reading from the connection using ReadNextPacket(). This means you have to use a go routine to either send or receive messages.

The problem is that when you call Ping() on a different go routine, you will get a data race – the Ping() implementation calls ReadNextPacket(). Within this method the LastReceivedHeader field is written – you get a data race because this field is written on 2 different go routines.

Any ideas on how to avoid that?

@soypat
Copy link
Owner

soypat commented Apr 26, 2023

Hey again! Fixing this is high on my priority list this week. I'm thinking of breaking the Client API to reach a much better usage pattern- how would you feel about this?

My reasons for this change are because I wrote this library before learning about the connection state pattern which I feel would make the library more robust and easier to use concurrently like you say.

Basically this would allow you to call ping asynchronously without worrying about the race condition which would be taken care by the connection state type. I've started work on the dev client-rewrite branch

@brutella
Copy link
Contributor Author

Fixing this is high on my priority list this week. I'm thinking of breaking the Client API to reach a much better usage pattern- how would you feel about this?

This sounds great. 👍
Please let me know when the refactoring is done so that I can take a closer look.

@soypat
Copy link
Owner

soypat commented Apr 27, 2023

Refactoring is done- I've yet to test changes though. Take a look over at #5

@soypat
Copy link
Owner

soypat commented May 8, 2023

@brutella Just curious- did you manage to get up and running with the PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants