Passing data between threads using a singleton - c++

Let me quickly explain what I'm trying to do. I currently have a program consisting of 2 threads. One worker thread and one GUI thread, the worker thread is collecting sensor data at 2kHz and the GUI thread visualize the collected data. The program is written in c++ using the Qt framework.
I have already tried the signal and slot option, I did this by passing a Qvector<PointF> as a signal in my worker thread to a slot in my GUI thread. But then I had a problem with "choppy data", while the data was being plotted my worker was stopped.
I then thought of using a singleton to pass data between the two threads, and here comes the main question; is using a singleton a good solution in this case? Or is there a better way to solve the problem?
I have already tested the concept by using a global Qvector<PointF> and a global mutex to protect the data but as global variables are frowned upon I thought of using a singleton instead.
Best regards

No, that is not what singletons were meant for. You have two threads, just provide a shared mechanism for moving data from one to the other, and make that mechanism available to both threads.

Related

Passing Pointers to Data Between Threads With Signal/Slot and Without Concurrent Modification in Qt

I have a worker thread object living in a different thread from my main GUI thread created as in the code at the bottom. I need to pass data between the threads without copying the data since the data is quite large (in this case a tree for use in a QAbstractItemModel so don't know how I'd copy it anyways...) and thus will pass a pointer to the data. This will be done using signals and slots. If the main GUI thread and the worker thread only ever process the data during their turn, do I need synchronization primitives/mutexes?
So the logic flow is like this. The worker threads constructs the data, then passes control to the GUI thread with a signal/slot connection. After this signal/slot connection the worker thread no longer does anything with the data. Control lies exclusively in the main GUI thread. Once the program has to process the data it again passes a pointer to the data to worker thread via signal/slot to be processed. After this signal/slot connection the GUI thread no longer does anything with the data. Considering the threads take their turns and signal/slot connections are thread-safe do I need synchronization primitives/mutexes at all?
workerThread = new QThread(this);
workerThread->start();
worker = new Worker;
worker->moveToThread(workerThread);
The GUI thread is called the master thread in general in the context of QT. This master thread has a living event queue. This queue is thread-safe as a result you do not need any synchronization here. However, you are sharing a common memory field among the threads, including your master and worker threads. Here you need to be careful about the shared data in some cases. Let me clarify it by giving some examples.
First of all, if you are sure that there is only one thread working on the data shared at the same time then you do not need any synchronization at all. In some cases, you may want to handle error cases in both threads. In these cases, you may want to access the shared data directly in either thread. As a result, you will need some locking mechanisms but I do not suggest you this approach.
I think the safest way to deal with this is by using event-driven architecture and I reckon that you are already doing this in your design. Just signal your master thread from one worker thread and do nothing in your worker thread until you get an event from the master thread and vice verse. I assume you have only one worker thread in your system.
Please note that your worker thread has also a living event queue already.
As a conclusion, if you have a clear patter and flow in your design with respect to the shared data process then you will not need any locking mechanism.

Thread-safe timing to align data collected in multiple threads- does QElapsedTimer work?

I'm working on an application (c++) that utilizes multiple types of hardware to simultaneously collect data of various types. The common usage pattern is to run the different interfaces to these devices (eye-tracking, motion-tracking, visualization, etc.) each in its own thread, so they mess with each other as little as possible. I don't a need a guarantee of super-precise timing of when the threads actually execute, which I understand would require hardware timers. What I'm looking to do, though, is have threads be able to query a central timer of some kind, which they can use periodically to add time-stamps to the collected data, so the data can be (semi-precisely) aligned later for analysis. Millisecond-scale precision is fine for this purpose.
The application uses Qt for gui purposes, so I thought QElapsedTimer would be a potential solution. However, the docs state that all methods are reentrant, not thread-safe. Am I correct that this necessitates a unique QElapsedTimer object for each thread that wishes to use this type of timing functionality? If this is the case, my approach would be to require each thread to initialize timing in a blocking function (executed in the main thread). Initialization would involve creating a wrapper object which combines a timer + an offset from the "main" timer, so that any/all timers created are "synchronized" to the main timer. This would be done in the main thread in order to obtain the offset from the non-threadsafe original timer.
Is this a reasonable approach, or is there a better "standard" (design-pattern) approach that I should use instead? Or, is there a different library that would better suit my purposes? Currently I'm working on Windows (7 and XP), but the application eventually is slated to be cross-platform.
In Qt you have convenient classes such as QMutexLocker for making synchronous calls. So you can use QMutexLocker along with QMutex in order to mark the function as thread safe, and then you can use QElapsedTimer across threads without any problems.
Reentrant means you need to have at least one different instance for each thread if you want to access simultaneously. You can also use QDateTime for generating timestamps, but that is not thread safe as well. I think therefore it would be better to mutex the access to that method.

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!
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.
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.

passing variable to a thread after it already started

i am newbie in C++ and boost.
As part of my master thesis, i wrote a program which simulate a statistical model. During the computation, i use boost::thread to process my "center of mass vector", for saving some computation time. So far so good.
Now, i would like to take each result from the boost::thread (each time one element) and pass it to a running thread, which is going to preform recursive regression.
My questions:
how can i pass my new computed element to the existing thread?
how could i "wake-up" the thread, when i pass the new element?
i would be happy if someone could point me to an existing example.
the simplest possible way is to use std::queue, boost::mutex and boost::conditional_variable. wrap any access to queue by mutex, after pushing to queue call conditional_variable.notify_one(). in consumer thread wait on conditional_variable until any result is ready, then process it.
A proven way to control a thread from another thread is to send messages via a combination of a queue with a conditional variable. Unfortunately, boost::thread doesn't provide a standard solution and there are a couple of tricky things when implementing (possible deadlocks, behaviour when queue is full, use polymorphic messages...)
You should use mutex and/ro semaphore to synchronize your threads and lock variable to achieve thread-safe communication. Just note that all threads in your process share the same memory so you can access the same data, but you have to do it in a thread-safe way.
I'm not sure if boost library implements any threading primitives, but here is a good tutorial about multi-threading programming using POSIX threads - http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html

Boost::Thread or fork() : Multithreaded HTTP Proxy

I'm testing boost::thread on a system. It happens that I needed to act as a fork(), because one thread modifies the other variables, even member variables of class
I do the project using fork() or is there some alternative still using boost::thread?
Basically I run this program in Linux and maybe FreeBSD.
It is an http proxy,accept() in main thread, and a function that accepts a class (where there is the file descriptor socket) in a secondary thread that makes the service.
Is there a better way to implement a proxy?
fork() spawns a process which have independent memory regions. Changed must be mediate through IPC.
boost::thread create a thread which can share memory.
They are not comparable.
To create thread-local storage, use boost::thread_specific_ptr.
See http://www.boost.org/doc/libs/1_42_0/doc/html/thread/thread_local_storage.html.
(You may also decorate a global variable as __thread int xyz; to make it thread-local, if the compiler and architecture can support it.)
It sounds like you are trying to allow multiple threads to alter global variables without each others' changes affecting any of the other threads. By forking, the entire memory space of your application is basically copied and each branch of the fork has its own variables and the two branches cannot communicate except through IPC.
If you want to use boost::thread, you'll have to do this copying yourself if you don't want threads to affect each other since the same memory space is common among all threads. You could just create the variables local to each thread function.
Using threads instead of forking will be much more flexible especially when you want to start letting the threads share data. If you want to have variables that all of the threads can change, they should be protected by mutex locks when being changed so that only one thread can change a variable at one time.