Consider the following szenario:
boost::asio each in its own threadclass DataConnection wrapped in a std::thread
class StatConnection also wrapped in a std::thread For counting connections (and other small data pieces) my idea was to use a static variable inside a namespace like:
#include <atomic>
namespace app {
namespace status {
static std::atomic<long> counter = 0;
}
}
This works fine for the DataConnection class. Here I increment counter in the c'tor and see the value increments.
But counter in my StatConnection class is always 0
Why can this happen?
I've tried some alternatives:
std::atomic<long> for static volatile long: Did not made a difference. static keyword.Then I got linker errors:
multiple definition of `app::status::searchtime'
./src/status/Status.o:/[...]/include/status/Status.hpp:16: first defined here
[...]
So why is the value of count different between threads?
static in namespace scope introduces internal linkage, so each translation unit will have its own copy of counter – quite the opposite of what you actually want!
Use extern instead, in the header:
//foo.h:
#include <atomic>
namespace app {
namespace status {
extern std::atomic<long> counter;
}
}
Then define the variable in one translation unit:
//foo.cpp:
#include "foo.h"
namespace app {
namespace status {
std::atomic<long> counter{0L};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With