Acapello
Acapello

Reputation: 127

How to predefine <atomic> variable?

I'm doing homework on multithreading and have such template(paste part of it, which i should change):

...
class MeanCounter : public MeanCounterBase {
public:

...
};
...

I need to use <atomic> and predefine it in class.

What I did:

class MeanCounter : public MeanCounterBase {
public:
  std::atomic<unsigned> W;

  void MeanCounterBase () {
    W.store(0);
  }
private:
...
};
...

But it didn't work at all! Program compile without mistakes. However in all threads at start W is not equal 0. What am I doing wrong?

Upvotes: 0

Views: 114

Answers (3)

SergeyA
SergeyA

Reputation: 62553

Your problem is here:

  void MeanCounterBase () {
    W.store(0);
  }

This is just a function inside MeanCounter class, and I doubt you ever call it. What you probably want, is a constructor for MeanCounter:

 MeanCounter() : W(0) { }

Upvotes: 3

Mark B
Mark B

Reputation: 96233

I think you may have meant MeanCounter() instead of void MeanCounterBase () to declare a child class constructor that initializes the atomic value. I'm not very familiar with atomics but I think you could initialize it in the initializer list instead of the constructor body.

Upvotes: 1

knivil
knivil

Reputation: 805

One way: Implement a constructor for mean counter that will set W to 0. Another way: Use a default member initializer.

Upvotes: 0

Related Questions