mardi 14 juin 2022

How to communicate betwwen threads with a constant interval

Now I have two threads, and thread1 querys while thread2 responses, and every query/response happens with the interval of 1min. But the query events are all in some queue that I cannot manually control the interval when to send them. So I think I can use thread synchronization to control the interval that I want.

Global:

mutex mut;
condition_variable cond;
atomic_bool query_end;

In thread1:

void query()
{
    auto start_time = steady_clock::now();
    lock_guard<mutex> lock(mut);
    if (!cond.wait_for(lock, std::chrono::minutes(1), [this] {return query_end.load();}))
    {
        print("timeout");
    }
    else
    {
        auto end_time = steady_clock::now();
        auto cost_time = duration_cast<milliseconds>(end_time - start_time).count();
        auto interval = Config::get_instance().get_query_interval();
        if (cost_time <= interval)
        {
            //sleep till 1min interval
            this_thread::sleep_for(milliseconds(interval - cost_time));
        }
        query_end = false;
    }
}

In thread 2:

void end_query()
{
    do something... and it runs within 1min..

    {
        lock_guard<mutex> lock(mut);
        query_end = true;
    }
    cond.notify_one();
}

The question is : the codes could work as I expected, but is there any simple(and more efficient) way to implement? As seen, the variable 'query_end' just plays as a predicate to prevent spurious wakeup but with no other actual meanings.

Aucun commentaire:

Enregistrer un commentaire