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

MQTTClient Thread-safety: Publishing #2078

Closed
fazho opened this issue Sep 10, 2024 · 1 comment
Closed

MQTTClient Thread-safety: Publishing #2078

fazho opened this issue Sep 10, 2024 · 1 comment
Labels
question It is a question regarding the project

Comments

@fazho
Copy link
Contributor

fazho commented Sep 10, 2024

Describe your question

Continuing the question from this thread: #2077
Could you please dive a little deeper into why it is unsafe for multi-threading?
 
Also what would be your recommended workaround for my scenario? Should I implement locks on the MQTT clients or could you point me to a thread-safe MQTT client? Basically I want to implement a MQTT client cache so I don't need to repeatedly connect and disconnect an MQTT client. But this cache will be shared by multiple threads, meaning it's likely those threads could use the same MQTT client to publish messages simultaneously.

@chkr1011

Which project is your question related to?

  • Client
@chkr1011
Copy link
Collaborator

chkr1011 commented Jan 5, 2025

You must synchronize the access to the MQTT client. There are different ways of doing this. One solution is to use a semaphore (SemaphoreSlim) to ensure that only a single thread is accessing the client. Another way is to start a worker thread which will process pending items from a queue and sends them. The other threads will only add items to that queue (also requires synchronization).

@chkr1011 chkr1011 closed this as completed Jan 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question It is a question regarding the project
Projects
None yet
Development

No branches or pull requests

2 participants