Mst137 Mst137 - 3 months ago 22
C Question

Threading to read COM ports with libmodbus

I am completely new to threading in C so wanted to check my idea was valid and relatively straightforward to program before starting on it. I want to write a program that can read from 2 COM ports simultaneously on two different threads (One thread per COM port) using Modbus RTU. I am relatively proficient using libmodbus functions etc it is just the threading part I require help with.

So, a few questions:
1) Is this possible to implement relatively easily (any examples no matter how simple would be much appreciated), and if so what considerations with regards to memory will need to be made?

2) Which relevant header files are required to implement multithreading in C?

Answer

So, a few questions: 1) Is this possible to implement relatively easily (any examples no matter how simple would be much appreciated)

Threading is a rather advanced topic in itself, and then you also have the system-specific ways of using a COM port. You'll have to study multi-threading and the OS-specific COM port library routines. It is not trivial.

what considerations with regards to memory will need to be made?

Shouldn't be a concern, except that you might want to implement some buffer system, which in turn must be protected by mutexes if used by multiple threads.

Which relevant header files are required to implement multithreading in C?

Depends on the system. For Linux and other POSIX systems, use pthreads (POSIX threads) from pthread.h. They may or may not be supported by a Windows compiler. Otherwise, Windows uses its own thread routines, CreateThread etc. RAD tools like Visual Studio or C++ Builder have wrapper classes around CreateThread. Other systems might have different libraries.

There was an attempt to standardize threading with the C11 standard, but that one is still in the experimental phase and we have yet to tell if it will be used or turn out a fiasco - few if any compilers support C11 threads. For now, pthreads is the most used industry standard.

Comments