I am using microsoft visual express.
I have viewed the accepted answer for this question and it seems to not be doing what I want it to do.
This is the function
Use std::thread
with this function:
#include <thread>
void foo() {
// your code
}
int main() {
std::thread thread(foo);
thread.join();
return 0;
}
What you want is a std::thread
as I mentioned in my comment. But also note you need a synchronization mechanism to prevent concurrent access for your global variables:
double time_counter = 0;
clock_t this_time = clock();
clock_t last_time = this_time;
const int NUM_SECONDS = 1;
std::mutex protect; // <<<<
void repeat() {
while (1) {
this_time = clock();
time_counter += (double)(this_time - last_time);
last_time = this_time;
if (time_counter > (double)(NUM_SECONDS * CLOCKS_PER_SEC)) {
time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC);
std::lock_guard<std::mutex> lock(protect); // <<<<
rockSecPast++;
}
}
}
and do the same in your main thread
std::thread t(repeat);
t.detach();
// ....
int currentRockSecPast = 0;
{
// read the asynchronously updated value safely
std::lock_guard<std::mutex> lock(protect);
currentRockSecPast = rockSecPast;
}
If I were you I'd put all that mess from above together in a separate class.