Global variable in namespace - values ​​vary by stream

Consider the following scenario:

  • 2 different network ports through boost::asioeach in its own stream
  • 1 port receives and processes data - class DataConnectionwrapped instd::thread
  • 1 port is intended for sending statistics class StatConnection, also wrapped instd::thread

To count compounds (and other small fragments), my idea was to use a variable staticinside namespace, for example:

#include <atomic>

namespace app {
 namespace status {
   static std::atomic<long> counter = 0; 
 }
}

This is great for the class DataConnection. Here I increment counterin c'tor and see increment values.

But counterin my class StatConnectionalways0

Why could this happen?

I tried several alternatives:

  • exchange std::atomic<long>for static volatile long: has not changed.
  • static.

:

multiple definition of `app::status::searchtime'
./src/status/Status.o:/[...]/include/status/Status.hpp:16: first defined here
[...]

, count ?

+5
1

static , counter – , !

extern :

//foo.h:
#include <atomic>

namespace app {
    namespace status {
        extern std::atomic<long> counter;
    }
}

:

//foo.cpp:
#include "foo.h"

namespace app {
    namespace status {
        std::atomic<long> counter{0L};
    }
}
+9

All Articles