5 years, 8 months ago.

Best way to share data with RTOS

I'm working on a project that has several threads, and I'm wondering what the best way to share data between them is. As an example, lets say I had 3 threads: the main thread (boots up and shuts down), a UI thread (drives a display-based user interface), and a battery thread (monitors a lithium battery). Every second or so, I want the battery thread to read the current battery information, and inform the other two threads that the information has changed. Now, the way I see it there's two competing ways that I could do this:

Option A: Global Data Struct

For option A, I create a global data struct that holds the latest battery data, and protect it with a mutex. The battery thread checks the battery every second or so, and stores the data in the global struct. If anything has changed, the battery thread signals the other two threads that the data struct has been changed.

or...

Option B: Queue/Mailbox

For option B, I equip the main and UI threads with specific battery info queues. The battery thread still checks on the battery every second or so, but the data is copied into the queues rather than a global struct.

Any thoughts? What's the most traditional/preferred approach and why? Thanks!

1 Answer

5 years, 8 months ago.

The use of a Queue is the clean way. The data is isolated between the threads. Using a Queue will need memory to copy the data. If you are working with big data it make sense to use a global data struct and some mutex. But you have to think about your design to avoid deadlocks and data integrity if more threads are using the same data.

Ok, so if I have USB thread that only accesses the data when a desktop application requests it, should I still give it a queue and just have it keep the latest version of the information? Also, is it better practice to have a single queue for all incoming data, or separate queues, one for each data type?

posted by Neil Thiessen 02 Apr 2014