I suppose you can rearrange your approach, avoiding recursion. The following program
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
using namespace std;
using namespace std::chrono_literals;
void do_something()
{
cout << "do something..." << endl;
}
void control_thread(std::atomic<bool> & stop)
{
while (!stop)
{
this_thread::sleep_for(1s);
do_something();
}
}
int main()
{
std::atomic<bool> stop{false};
thread ct(control_thread, ref(stop));
for (size_t n = 0; n<10; ++n)
{
cout << "main thread, iteration " << n << ", sleeping..." << endl;;
this_thread::sleep_for(2.5s);
}
stop = true;
cout << "wating for the thread to join..." << endl;
ct.join();
cout << "finished" << endl;
}
produces
main thread, iteration 0, sleeping...
do something...
do something...
main thread, iteration 1, sleeping...
do something...
do something...
main thread, iteration 2, sleeping...
do something...
do something...
do something...
main thread, iteration 3, sleeping...
do something...
do something...
main thread, iteration 4, sleeping...
do something...
do something...
do something...
main thread, iteration 5, sleeping...
do something...
do something...
main thread, iteration 6, sleeping...
do something...
do something...
do something...
main thread, iteration 7, sleeping...
do something...
do something...
main thread, iteration 8, sleeping...
do something...
do something...
do something...
main thread, iteration 9, sleeping...
do something...
do something...
wating for the thread to join...
do something...
finished