I'm trying to implement a blocking counter that may have several readers and writers at the same time:
class BlockingCounter {
public:
BlockingCounter(int count) : count_(count) {
// init lock_;
}
~BlockingCounter() {
// destroy lock_;
}
void Increment() {
pthread_rwlock_wrlock(&lock_);
count_++;
pthread_rwlock_unlock(&lock_);
}
void Decrement() {
pthread_rwlock_wrlock(&lock_);
count_--;
pthread_rwlock_unlock(&lock_);
}
int GetCount() {
pthread_rwlock_rdlock(&lock_);
int count = count_;
pthread_rwlock_unlock(&lock_);
return count;
}
private:
pthread_rwlock_t lock_;
int count_;
};
Does this code have problems under multi-threading circumstances?
I intended to use it like this:
Main thread:
BlockingCounter *counter = new BlockingCounter(10);
// Here 10 threads are started. See code below.
while (counter->GetCount() > 0) {
ConditionVar.wait();
}
// Main thread resumes execution.
Other 10 thread(s):
// Do stuff
counter.Decrement();
ConditionVar.notify();
std::atomic, you won't need all that. \$\endgroup\$