Consider the following szenario:
- 2 different network-ports via
boost::asioeach in its own thread - 1 port is receiving and processing data –
class DataConnectionwrapped in astd::thread - 1 port is for sending statistics
class StatConnectionalso wrapped in astd::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:
- exchanging
std::atomic<long>forstatic volatile long: Did not made a difference. - using the namespace without
statickeyword.
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?
staticin namespace scope introduces internal linkage, so each translation unit will have its own copy ofcounter– quite the opposite of what you actually want!Use
externinstead, in the header:Then define the variable in one translation unit: