C++ run asynch function every second












1















I am developing a C++ application using Qt and I need to run a function asynchronously every second.



The application works this way:




  • the user start a functionallity;

  • the application call the specific function asynchronously letting the user doing something else in the meantime;

  • when the user stops the functionallity, the application stops calling the function.


For other functions I used Qt integrated SLOTS and SIGNALS, like this:



connect(timer, SIGNAL(timeout()), this, SLOT(updateView()));
timer->start(200);


but for this particular function I wanted to use only C++ functionallity like thread, mutex, future, promise and asynch.



I tried something like this:



if(cmd == start) {
std::future<void> fn = async(std::launch::async, (){
// some code here
});
}


This way, every time the user clicks start the application calls the lambda function.



Now I want that function to be called every second until the user clicks stop without avoiding him to do something else in the meantime.



Can someone help me?










share|improve this question























  • Create a new std::thread, a mutex, a condition variable, and a bool flag. The thread locks the mutex uses wait_for() to wait 1 second on a condition variable, check the flag, call your function if it's not set, then try again. When you no longer need this to happen, lock the mutex, set the flag, notify the condition variable, and join() your thread. For extra credit, check the flag before and after waiting on the condition variable. Mission accomplished.

    – Sam Varshavchik
    Nov 21 '18 at 13:31











  • @SamVarshavchik thank you! I will try to implement a solution like the one you are suggesting for I want to master thread locks with mutexes and condition variables

    – ambdere
    Nov 21 '18 at 14:11
















1















I am developing a C++ application using Qt and I need to run a function asynchronously every second.



The application works this way:




  • the user start a functionallity;

  • the application call the specific function asynchronously letting the user doing something else in the meantime;

  • when the user stops the functionallity, the application stops calling the function.


For other functions I used Qt integrated SLOTS and SIGNALS, like this:



connect(timer, SIGNAL(timeout()), this, SLOT(updateView()));
timer->start(200);


but for this particular function I wanted to use only C++ functionallity like thread, mutex, future, promise and asynch.



I tried something like this:



if(cmd == start) {
std::future<void> fn = async(std::launch::async, (){
// some code here
});
}


This way, every time the user clicks start the application calls the lambda function.



Now I want that function to be called every second until the user clicks stop without avoiding him to do something else in the meantime.



Can someone help me?










share|improve this question























  • Create a new std::thread, a mutex, a condition variable, and a bool flag. The thread locks the mutex uses wait_for() to wait 1 second on a condition variable, check the flag, call your function if it's not set, then try again. When you no longer need this to happen, lock the mutex, set the flag, notify the condition variable, and join() your thread. For extra credit, check the flag before and after waiting on the condition variable. Mission accomplished.

    – Sam Varshavchik
    Nov 21 '18 at 13:31











  • @SamVarshavchik thank you! I will try to implement a solution like the one you are suggesting for I want to master thread locks with mutexes and condition variables

    – ambdere
    Nov 21 '18 at 14:11














1












1








1








I am developing a C++ application using Qt and I need to run a function asynchronously every second.



The application works this way:




  • the user start a functionallity;

  • the application call the specific function asynchronously letting the user doing something else in the meantime;

  • when the user stops the functionallity, the application stops calling the function.


For other functions I used Qt integrated SLOTS and SIGNALS, like this:



connect(timer, SIGNAL(timeout()), this, SLOT(updateView()));
timer->start(200);


but for this particular function I wanted to use only C++ functionallity like thread, mutex, future, promise and asynch.



I tried something like this:



if(cmd == start) {
std::future<void> fn = async(std::launch::async, (){
// some code here
});
}


This way, every time the user clicks start the application calls the lambda function.



Now I want that function to be called every second until the user clicks stop without avoiding him to do something else in the meantime.



Can someone help me?










share|improve this question














I am developing a C++ application using Qt and I need to run a function asynchronously every second.



The application works this way:




  • the user start a functionallity;

  • the application call the specific function asynchronously letting the user doing something else in the meantime;

  • when the user stops the functionallity, the application stops calling the function.


For other functions I used Qt integrated SLOTS and SIGNALS, like this:



connect(timer, SIGNAL(timeout()), this, SLOT(updateView()));
timer->start(200);


but for this particular function I wanted to use only C++ functionallity like thread, mutex, future, promise and asynch.



I tried something like this:



if(cmd == start) {
std::future<void> fn = async(std::launch::async, (){
// some code here
});
}


This way, every time the user clicks start the application calls the lambda function.



Now I want that function to be called every second until the user clicks stop without avoiding him to do something else in the meantime.



Can someone help me?







c++ multithreading c++11 asynchronous






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 13:27









ambdereambdere

296




296













  • Create a new std::thread, a mutex, a condition variable, and a bool flag. The thread locks the mutex uses wait_for() to wait 1 second on a condition variable, check the flag, call your function if it's not set, then try again. When you no longer need this to happen, lock the mutex, set the flag, notify the condition variable, and join() your thread. For extra credit, check the flag before and after waiting on the condition variable. Mission accomplished.

    – Sam Varshavchik
    Nov 21 '18 at 13:31











  • @SamVarshavchik thank you! I will try to implement a solution like the one you are suggesting for I want to master thread locks with mutexes and condition variables

    – ambdere
    Nov 21 '18 at 14:11



















  • Create a new std::thread, a mutex, a condition variable, and a bool flag. The thread locks the mutex uses wait_for() to wait 1 second on a condition variable, check the flag, call your function if it's not set, then try again. When you no longer need this to happen, lock the mutex, set the flag, notify the condition variable, and join() your thread. For extra credit, check the flag before and after waiting on the condition variable. Mission accomplished.

    – Sam Varshavchik
    Nov 21 '18 at 13:31











  • @SamVarshavchik thank you! I will try to implement a solution like the one you are suggesting for I want to master thread locks with mutexes and condition variables

    – ambdere
    Nov 21 '18 at 14:11

















Create a new std::thread, a mutex, a condition variable, and a bool flag. The thread locks the mutex uses wait_for() to wait 1 second on a condition variable, check the flag, call your function if it's not set, then try again. When you no longer need this to happen, lock the mutex, set the flag, notify the condition variable, and join() your thread. For extra credit, check the flag before and after waiting on the condition variable. Mission accomplished.

– Sam Varshavchik
Nov 21 '18 at 13:31





Create a new std::thread, a mutex, a condition variable, and a bool flag. The thread locks the mutex uses wait_for() to wait 1 second on a condition variable, check the flag, call your function if it's not set, then try again. When you no longer need this to happen, lock the mutex, set the flag, notify the condition variable, and join() your thread. For extra credit, check the flag before and after waiting on the condition variable. Mission accomplished.

– Sam Varshavchik
Nov 21 '18 at 13:31













@SamVarshavchik thank you! I will try to implement a solution like the one you are suggesting for I want to master thread locks with mutexes and condition variables

– ambdere
Nov 21 '18 at 14:11





@SamVarshavchik thank you! I will try to implement a solution like the one you are suggesting for I want to master thread locks with mutexes and condition variables

– ambdere
Nov 21 '18 at 14:11












2 Answers
2






active

oldest

votes


















2














Using std::future suppose that your code executed once and you get some result in the future. So it is not your case.
Timer that you looking for may be implemented as stand-alone thread with infinite loop that periodically invoke your functor. Please look at this decision:
https://stackoverflow.com/a/30425945/149818






share|improve this answer



















  • 1





    Thank you! This is what I was looking for. I already wrote something like this but I forgot the existence of detach so I was able to call the fuction every second only in the main thread.

    – ambdere
    Nov 21 '18 at 13:57





















-1














One way ist std::thread. It is used to run another function asynchronous. Once started it finishes after returning from the function you gave it so you have to use a loop to control it.



To prevent race conditions i usually use a std::atomic variable to control that loop.



If the thread object can be called from multiple parallel threads you sould protect it with a mutex to prevent multiple parallel accesses.



One example implementation could look like this:



class MyParallelJob
{
private:
std::thread* _thread = nullptr;
std::atomic<bool> _threadRunning = false;

public:
void startThread()
{
if(_thread == nullptr) // This condition prevents the thread from being started twice.
{
_threadRunning = true; // Set thread loop condition to true
_thread = new std::thread(parallel, this); // Create thread
}
}

void stopThread()
{
if(_thread != nullptr) // Prevents from stopping an stopped thread
{
_threadRunning = false; // Set thread loop condition to false
_thread.join(); // Wait for thread to finish
delete _thread; // Delete thread
_thread = nullptr; // Set thread pointer to nullptr
}
}

void parallel() // Function valled by thread
{
while(_threadRunning == true) // While thread loop condition variable is true(=> stopThread() not called)...
{
//Asynchronous jobs here. (eg. function call)
sleep(1); // Sleep one second
}

}
}





share|improve this answer


























  • This does not show how to fire off a function every second (not the down voter)

    – NathanOliver
    Nov 21 '18 at 13:50











  • @NathanOliver - I thought sleeping one second would be trivial. However, i added it now to make it more obvious.

    – Detonar
    Nov 21 '18 at 13:52











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413092%2fc-run-asynch-function-every-second%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














Using std::future suppose that your code executed once and you get some result in the future. So it is not your case.
Timer that you looking for may be implemented as stand-alone thread with infinite loop that periodically invoke your functor. Please look at this decision:
https://stackoverflow.com/a/30425945/149818






share|improve this answer



















  • 1





    Thank you! This is what I was looking for. I already wrote something like this but I forgot the existence of detach so I was able to call the fuction every second only in the main thread.

    – ambdere
    Nov 21 '18 at 13:57


















2














Using std::future suppose that your code executed once and you get some result in the future. So it is not your case.
Timer that you looking for may be implemented as stand-alone thread with infinite loop that periodically invoke your functor. Please look at this decision:
https://stackoverflow.com/a/30425945/149818






share|improve this answer



















  • 1





    Thank you! This is what I was looking for. I already wrote something like this but I forgot the existence of detach so I was able to call the fuction every second only in the main thread.

    – ambdere
    Nov 21 '18 at 13:57
















2












2








2







Using std::future suppose that your code executed once and you get some result in the future. So it is not your case.
Timer that you looking for may be implemented as stand-alone thread with infinite loop that periodically invoke your functor. Please look at this decision:
https://stackoverflow.com/a/30425945/149818






share|improve this answer













Using std::future suppose that your code executed once and you get some result in the future. So it is not your case.
Timer that you looking for may be implemented as stand-alone thread with infinite loop that periodically invoke your functor. Please look at this decision:
https://stackoverflow.com/a/30425945/149818







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 21 '18 at 13:37









DewfyDewfy

17.4k1157105




17.4k1157105








  • 1





    Thank you! This is what I was looking for. I already wrote something like this but I forgot the existence of detach so I was able to call the fuction every second only in the main thread.

    – ambdere
    Nov 21 '18 at 13:57
















  • 1





    Thank you! This is what I was looking for. I already wrote something like this but I forgot the existence of detach so I was able to call the fuction every second only in the main thread.

    – ambdere
    Nov 21 '18 at 13:57










1




1





Thank you! This is what I was looking for. I already wrote something like this but I forgot the existence of detach so I was able to call the fuction every second only in the main thread.

– ambdere
Nov 21 '18 at 13:57







Thank you! This is what I was looking for. I already wrote something like this but I forgot the existence of detach so I was able to call the fuction every second only in the main thread.

– ambdere
Nov 21 '18 at 13:57















-1














One way ist std::thread. It is used to run another function asynchronous. Once started it finishes after returning from the function you gave it so you have to use a loop to control it.



To prevent race conditions i usually use a std::atomic variable to control that loop.



If the thread object can be called from multiple parallel threads you sould protect it with a mutex to prevent multiple parallel accesses.



One example implementation could look like this:



class MyParallelJob
{
private:
std::thread* _thread = nullptr;
std::atomic<bool> _threadRunning = false;

public:
void startThread()
{
if(_thread == nullptr) // This condition prevents the thread from being started twice.
{
_threadRunning = true; // Set thread loop condition to true
_thread = new std::thread(parallel, this); // Create thread
}
}

void stopThread()
{
if(_thread != nullptr) // Prevents from stopping an stopped thread
{
_threadRunning = false; // Set thread loop condition to false
_thread.join(); // Wait for thread to finish
delete _thread; // Delete thread
_thread = nullptr; // Set thread pointer to nullptr
}
}

void parallel() // Function valled by thread
{
while(_threadRunning == true) // While thread loop condition variable is true(=> stopThread() not called)...
{
//Asynchronous jobs here. (eg. function call)
sleep(1); // Sleep one second
}

}
}





share|improve this answer


























  • This does not show how to fire off a function every second (not the down voter)

    – NathanOliver
    Nov 21 '18 at 13:50











  • @NathanOliver - I thought sleeping one second would be trivial. However, i added it now to make it more obvious.

    – Detonar
    Nov 21 '18 at 13:52
















-1














One way ist std::thread. It is used to run another function asynchronous. Once started it finishes after returning from the function you gave it so you have to use a loop to control it.



To prevent race conditions i usually use a std::atomic variable to control that loop.



If the thread object can be called from multiple parallel threads you sould protect it with a mutex to prevent multiple parallel accesses.



One example implementation could look like this:



class MyParallelJob
{
private:
std::thread* _thread = nullptr;
std::atomic<bool> _threadRunning = false;

public:
void startThread()
{
if(_thread == nullptr) // This condition prevents the thread from being started twice.
{
_threadRunning = true; // Set thread loop condition to true
_thread = new std::thread(parallel, this); // Create thread
}
}

void stopThread()
{
if(_thread != nullptr) // Prevents from stopping an stopped thread
{
_threadRunning = false; // Set thread loop condition to false
_thread.join(); // Wait for thread to finish
delete _thread; // Delete thread
_thread = nullptr; // Set thread pointer to nullptr
}
}

void parallel() // Function valled by thread
{
while(_threadRunning == true) // While thread loop condition variable is true(=> stopThread() not called)...
{
//Asynchronous jobs here. (eg. function call)
sleep(1); // Sleep one second
}

}
}





share|improve this answer


























  • This does not show how to fire off a function every second (not the down voter)

    – NathanOliver
    Nov 21 '18 at 13:50











  • @NathanOliver - I thought sleeping one second would be trivial. However, i added it now to make it more obvious.

    – Detonar
    Nov 21 '18 at 13:52














-1












-1








-1







One way ist std::thread. It is used to run another function asynchronous. Once started it finishes after returning from the function you gave it so you have to use a loop to control it.



To prevent race conditions i usually use a std::atomic variable to control that loop.



If the thread object can be called from multiple parallel threads you sould protect it with a mutex to prevent multiple parallel accesses.



One example implementation could look like this:



class MyParallelJob
{
private:
std::thread* _thread = nullptr;
std::atomic<bool> _threadRunning = false;

public:
void startThread()
{
if(_thread == nullptr) // This condition prevents the thread from being started twice.
{
_threadRunning = true; // Set thread loop condition to true
_thread = new std::thread(parallel, this); // Create thread
}
}

void stopThread()
{
if(_thread != nullptr) // Prevents from stopping an stopped thread
{
_threadRunning = false; // Set thread loop condition to false
_thread.join(); // Wait for thread to finish
delete _thread; // Delete thread
_thread = nullptr; // Set thread pointer to nullptr
}
}

void parallel() // Function valled by thread
{
while(_threadRunning == true) // While thread loop condition variable is true(=> stopThread() not called)...
{
//Asynchronous jobs here. (eg. function call)
sleep(1); // Sleep one second
}

}
}





share|improve this answer















One way ist std::thread. It is used to run another function asynchronous. Once started it finishes after returning from the function you gave it so you have to use a loop to control it.



To prevent race conditions i usually use a std::atomic variable to control that loop.



If the thread object can be called from multiple parallel threads you sould protect it with a mutex to prevent multiple parallel accesses.



One example implementation could look like this:



class MyParallelJob
{
private:
std::thread* _thread = nullptr;
std::atomic<bool> _threadRunning = false;

public:
void startThread()
{
if(_thread == nullptr) // This condition prevents the thread from being started twice.
{
_threadRunning = true; // Set thread loop condition to true
_thread = new std::thread(parallel, this); // Create thread
}
}

void stopThread()
{
if(_thread != nullptr) // Prevents from stopping an stopped thread
{
_threadRunning = false; // Set thread loop condition to false
_thread.join(); // Wait for thread to finish
delete _thread; // Delete thread
_thread = nullptr; // Set thread pointer to nullptr
}
}

void parallel() // Function valled by thread
{
while(_threadRunning == true) // While thread loop condition variable is true(=> stopThread() not called)...
{
//Asynchronous jobs here. (eg. function call)
sleep(1); // Sleep one second
}

}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 21 '18 at 13:50

























answered Nov 21 '18 at 13:43









DetonarDetonar

986112




986112













  • This does not show how to fire off a function every second (not the down voter)

    – NathanOliver
    Nov 21 '18 at 13:50











  • @NathanOliver - I thought sleeping one second would be trivial. However, i added it now to make it more obvious.

    – Detonar
    Nov 21 '18 at 13:52



















  • This does not show how to fire off a function every second (not the down voter)

    – NathanOliver
    Nov 21 '18 at 13:50











  • @NathanOliver - I thought sleeping one second would be trivial. However, i added it now to make it more obvious.

    – Detonar
    Nov 21 '18 at 13:52

















This does not show how to fire off a function every second (not the down voter)

– NathanOliver
Nov 21 '18 at 13:50





This does not show how to fire off a function every second (not the down voter)

– NathanOliver
Nov 21 '18 at 13:50













@NathanOliver - I thought sleeping one second would be trivial. However, i added it now to make it more obvious.

– Detonar
Nov 21 '18 at 13:52





@NathanOliver - I thought sleeping one second would be trivial. However, i added it now to make it more obvious.

– Detonar
Nov 21 '18 at 13:52


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413092%2fc-run-asynch-function-every-second%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

ComboBox Display Member on multiple fields

Is it possible to collect Nectar points via Trainline?