The following content involves the concepts of synchronous and asynchronous.
Here is a C++ class that simulates a timer.

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
#include <thread>

// #define _GLIBCXX_USE_NANOSLEEP

class DelayRunTask
{
public:
    template <class callable, class... arguments>
    DelayRunTask(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));


        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after)); // std::this_thread::sleep_for not defined in gcc + ubuntu
            task();
        }
    }
};

void Show(int a)
{
    printf("%i\n", a);
}

int main()
{
    for( int i = 0; i < 10; ++i )
    {
        later(200, true, &test2, i+1);
    }

    printf("finished!\n");

    std::this_thread::sleep_for(std::chrono::seconds(5));
    return 0;
}

Output asynchronously.

finished!
5
4
7
9
1
8
6
2
10
3

To simulate a timer for sequentially outputting numbers, we can do it like this:

int main()
{
    for( int i = 0; i < 10; ++i )
    {
        later(200, false, &test2, i+1);
    }
    return 0;
}

/*
1
2
3
4
5
6
7
8
9
10
*/

We cannot execute the task of rendering frames by creating a new thread in this way because vtkRenderWindow::Render() cannot work in other threads.

Categories: CPlusPlus

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x