mercredi 22 février 2017

Using condition_variable in an array in C++

I have C++ code that looks like (I left out all irrelevant parts):

using namespace std;
int N = 8;
int values[N];
const condition_variable cvs[N];
void listener_thread(int index)
{
    int value = -1;
    while(/* still alive */)
    {
        {
            const condition_variable* cv = &cvs[index];
            unique_lock<mutex> lk(cv);
            cv->wait(lk, []{return values[index] != value;});
            value = values[index];
        }
        /* use value */
    }
}
void updater_thread()
{
    while(/* still alive */)
    {
        int input[N];
        /* read input */
        for(int i=0;i<N;++i)
        {
            const condition_variable* cv;
            {
                cv = &cvs[i];
                lock_guard<mutex> lk(cv);
                values[i] = input[i];
            }
            cv.notify_all();
        }
    }
}

The goal is to have a (possibly multiple) thread listen to a value in values at a given index. If a value changes, the thread that changes it will do a notify_all() for the corresponding condition_variable.

But this does not compile because the condition_variable is located in an array. I would like to have it in an array, because even though N is now constant, it may need to be adjustable/parametrized in the future. The compiler error is:

error: no matching function for call to ‘std::unique_lock<std::mutex>::unique_lock(const std::condition_variable*&)’
     unique_lock<mutex> lk(cv);
                             ^

Using the following code:

const condition_variable cv = cvs[index];

does not work either, because I suppose that condition_variable has to stay at the same location in memory. The error for that is:

error: use of deleted function ‘std::condition_variable::condition_variable(const std::condition_variable&)’
     const condition_variable cv = alarm_cv[listen_bit_index];
                                                            ^

How can I solve this while still keeping the condition_variable in an array/vector?

Note: This area of C++ is new to me, so maybe I'm doing this completely wrong.

Aucun commentaire:

Enregistrer un commentaire