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

Multi-threaded Modbus TCP Server: Issue with modbus_set_socket() and Context Handling #777

Open
Pcdwarf opened this issue Nov 7, 2024 · 0 comments

Comments

@Pcdwarf
Copy link

Pcdwarf commented Nov 7, 2024

Hello,

I’ve implemented a Modbus TCP server that accepts multiple concurrent client connections. For each new connection, the server spawns a new thread to handle the specific client’s requests.

Initially, I assumed that the listening socket was handled by a single Modbus context, and each client would be managed as an independent connection within this context.

Here’s what I did:

I passed the same Modbus context and unique clientSocket to each thread.
I used modbus_set_socket() within each thread, expecting that it would handle individual client connections independently.

Issue: It appears that modbus_set_socket() modifies a single property in the shared Modbus context rather than managing it on a per-thread basis. Consequently, when multiple threads attempt to set the socket within the same context, the behavior becomes inconsistent and connections get mixed up.

Questions:

Would it be viable to create a shallow copy of the Modbus context for each connection and then use modbus_set_socket() on each copy?
Is there a recommended approach to implementing multi-threaded handling of client connections, or is multi-threading considered problematic in libmodbus?

Any advice on best practices for this situation would be highly appreciated.

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

1 participant