考虑以下情况:
- 2个不同的网络端口,
boost::asio每个端口都在自己的线程中 - 1 个端口正在接收和处理数据 -
class DataConnection包裹在std::thread - 1 个端口用于发送统计信息
class StatConnection,也包含在std::thread
为了计算连接(和其他小数据块),我的想法是在类似的static内部使用一个变量namespace:
#include <atomic>
namespace app {
namespace status {
static std::atomic<long> counter = 0;
}
}
DataConnection这对班级来说很好。在这里,我counter在 c'tor 中递增并查看值递增。
但counter在我的StatConnection课上总是0
为什么会发生这种情况?
我尝试了一些替代方案:
- 交换
std::atomic<long>:static volatile long没有任何区别。 - 使用没有
static关键字的命名空间。
然后我得到链接器错误:
multiple definition of `app::status::searchtime'
./src/status/Status.o:/[...]/include/status/Status.hpp:16: first defined here
[...]
那么为什么线程之间的值count不同呢?