How can i do threads run in background?
-
Hello, I am working on a project that needs to run three functions in the background. The idea is that these functions run all the time, while running the main of the program. I thought about implementing it with threads, but looking at several tutorials I found that they all used the .join() function. From what I understand, the .join() function causes the thread to start running and until it finishes, the program does not continue to run.
Is there any way to make the thread run in the background? Or they know somehow that I don't use threads and also allow me to execute these functions in the background, it can also serve me.int main() { std::thread hilo1(function1); std::thread hilo2(function2); std::thread hilo3(function3); hilo1.join(); hilo2.join(); hilo3.join(); //rest of the code //the program continue runnig while the threads do things }
-
@Pordo
I suggest you start by reading Thread Support in Qt if you want to do threading in a Qt application, and many other articles. Yes you can have threads running in the background without having to wait on them. You can communicate with them via signals and slots.If you want a couple of really basic examples, https://www.bogotobogo.com/Qt/Qt5_QThreads_Creating_Threads.php and https://www.bogotobogo.com/Qt/Qt5_QtConcurrent_RunFunction_QThread.php look really simple.
-
@Pordo said:
From what I understand, the .join() function causes the thread to start running and until it finishes, the program does not continue to run.
No, that's not right. std::thread starts running in the constructor.
join() is a synchronization method, meaning it blocks current thread until the other thread finishes.So if you want to continue main thread while the three threads do their thing just switch the order:
int main() { std::thread hilo1(function1); std::thread hilo2(function2); std::thread hilo3(function3); // rest of the code // the program continue runnig while the threads do things // and when you're done wait for the other threads to finish hilo1.join(); hilo2.join(); hilo3.join(); }
-
OP doesn't give enough information to indicate what is best strategy: event dispatch, timer execution, or threads.