Kam
Kam

Reputation: 6008

Threads sharing data in C++

I have a GUI thread that needs information from another thread (IO Thread). IO thread all its doing is fetching information from serial port. Gui Thread all its doing is reading the fetches info and display them in a table.

I was thinking maybe, the IO thread should put the data in a global struct protected by a mutex and then the GUI thread should read from that struct. Is there a better implementation? Would the use of a critical section better than a mutex in this case?

Now I know I will get a reply saying why don't you use only the GUI thread to fetch IO data also, so I won't need multithreading. Yes, I know I am just trying to give a simple example to learn best practices :)

Thank you!

Upvotes: 0

Views: 402

Answers (2)

AndersK
AndersK

Reputation: 36082

One way to do that is let your IO thread post the input data to the GUI. Whenever you receive data on your IO thread you package it in a struct on the heap and post a custom message together with the address of the struct back to the GUI thread. IOW you create the GUI thread and then the IO thread passing the handle of the GUI thread to the IO thread to be used to send data back to the GUI. That way you do not need to care of about mutex/critical section but you either use the existing GUI message queue or create your own depending on what environment your project is supposed to run in.

Upvotes: 2

X-Istence
X-Istence

Reputation: 16667

What I suggest is two different instances of the same struct. When your IO thread is ready for the GUI thread to be updated, it grabs a mutex, copies it's struct into that of the GUI thread, unlocks the mutex and notifies the GUI thread that it should read an updated copy of the struct.

As for your critical section, that just refers to the concept of having sections of code that only one can be executing at a time. Mostly because you could otherwise get inconsistent state. The way you create a critical section is by gating it with an lock mutex and an unlock mutex.

Upvotes: 1

Related Questions