有没有办法在同一个线程中异步调用函数?

时间:2018-02-27 18:29:00

标签: c++ multithreading asynchronous

有没有办法只使用一个线程来模拟相同的行为?我有一个相当复杂的代码,现在我使用大约50行std :: lock_guard作为该计时器。我喜欢std :: launch :: deferred的方法,但在我的情况下,计时器不能返回任何内容。

int i = 0;
std::mutex mtx;

std::thread checker([&i, &mtx](){
    while (true) {
        mtx.lock();
        if (i == 5)
            std::cout << "Hello" << std::endl;
        mtx.unlock();
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
});

while (true) {
    mtx.lock();
    i = rand() % 10;
    mtx.unlock();
    std::this_thread::sleep_for(std::chrono::nanoseconds(100));
}

checker.join();

这是我尝试使用std :: launch :: deferred。它不起作用,因为future.get()阻止主线程

int i = 0;
std::future<void> future(std::async(std::launch::deferred, [&i](){
    std::cout << "Timer has started" << std::endl;
    while (true) {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        if (i == 5)
            std::cout << "Hello" << std::endl;
    }
}));
future.get();
std::cout << "Main thread has started" << std::endl;
while (true) {
    i = rand() % 10;
    std::this_thread::sleep_for(std::chrono::nanoseconds(100));
}

0 个答案:

没有答案