How to repeat an action with asynchronous timer every x seconds?

Hello again,

as the title say, i would like to repeate an action (a system beep, for example) every ten seconds.


Thank you very much
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>

std::atomic_flag cont = ATOMIC_FLAG_INIT;

struct beep_annoyingly
{
template <typename DURATION>
    void operator()(DURATION duration)
    {
        while(cont.test_and_set()) {
            std::cout << '\a';
            std::this_thread::sleep_for(duration);
        }
    }
};

int main()
{
    using namespace std::literals;
    cont.test_and_set();
    std::thread foo(beep_annoyingly(), 500ms);
    std::cout << "Press enter when you cannot handle this sound anymore";
    std::cin.get();
    cont.clear();
    foo.join();
}
Last edited on
Thank you.

Will this thread be executed asynchronously?

I mean... the while should not block the rest of the program.

Btw, i get:

main.cpp|1885|error: 'literals' is not a namespace-name|
using namespace std::literals;

Last edited on
As you can see output in main is placed after creating new thread with loop inside and it outputs correctly. Also you can hear beep while main function waits for input.
Topic archived. No new replies allowed.