Sunday, 15 July 2012

c++11 - Trying to use lambda functions as predicate for condition_variable wait method -



c++11 - Trying to use lambda functions as predicate for condition_variable wait method -

i trying create producer-consumer method using c++11 concurrency. wait method condition_variable class has predicate sec argument, thought of using lambda function:

struct limitedbuffer { int* buffer, size, front, back, count; std::mutex lock; std::condition_variable not_full; std::condition_variable not_empty; limitedbuffer(int size) : size(size), front(0), back(0), count(0) { buffer = new int[size]; } ~limitedbuffer() { delete[] buffer; } void add(int data) { std::unique_lock<std::mutex> l(lock); not_full.wait(l, [&count, &size]() { homecoming count != size; }); buffer[back] = data; = (back+1)%size; ++count; not_empty.notify_one(); } int extract() { std::unique_lock<std::mutex> l(lock); not_empty.wait(l, [&count]() { homecoming count != 0; }); int result = buffer[front]; front end = (front+1)%size; --count; not_full.notify_one(); homecoming result; } };

but getting error:

[error] capture of non-variable 'limitedbuffer::count'

i don't know much c++11 , lambda functions found out class members can't captured value. value though, capturing them reference, seems it's same thing.

in display of brilliance stored struct members values in local variables , used them in lambda function, , worked! ... or not:

int ct = count, sz = size; not_full.wait(l, [&ct, &sz]() { homecoming ct != sz; });

obviously destroying whole point of wait function using local variables since value assigned 1 time , fun part checking fellow member variables may, should , change. silly me.

so, choices? there way can create wait method has do, using fellow member variables? or forced not utilize lambda functions i'd have declare auxiliary functions work?

i don't why can't utilize members variables in lambda functions, since masters of universe dessigned lamba functions c++11 way, there must reason.

count fellow member variable. fellow member variables can not captured directly. instead, can capture this accomplish same effect:

not_full.wait(l, [this] { homecoming count != size; });

c++11 concurrency lambda synchronization condition-variable

No comments:

Post a Comment