12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- #pragma once
- #include <atomic>
- #include <mutex>
- class CUniqueId
- {
- public:
- CUniqueId();
- CUniqueId(const unsigned char &workerId, const unsigned char &datacenterId)
- {
- _workerId = workerId;
- _datacenterId = datacenterId;
- }
- ~CUniqueId();
- private:
- // 开始utc时间戳(2018-01-01 00:00:00.000);
- const unsigned long long _twepoch = 1514736000000;
- // 工作者占用位数;
- const unsigned char _workerIdBits = 5;
- // 支持的最大工作者id,结果是31;
- const unsigned char _maxWorkerId = -1L ^ (-1L << _workerIdBits);
- // 数据中心占用位数;
- const unsigned char _datacenterIdBits = 5;
- // 支持的最大数据中心id,结果是31;
- const unsigned char _maxDatacenterId = -1L ^ (-1L << _datacenterIdBits);
- // 序列占用位数;
- const unsigned char _sequenceBits = 12;
- // 工作者向左移12位;
- const unsigned char _workerIdShift = _sequenceBits;
- // 数据中心向左移17位;
- const unsigned char _datacenterIdShift = _workerIdShift + _workerIdBits;
- // 时间戳向左移22位;
- const unsigned char _timestampleftShift = _datacenterIdShift + _datacenterIdBits;
- // 生成的序列掩码,4095;
- const unsigned short _sequenceMask = -1L ^ (-1L << _sequenceBits);
- // 工作id;
- unsigned char _workerId;
- // 数据中心id;
- unsigned char _datacenterId;
- // 序列值;
- unsigned short _sequence;
- // 上一次的时间戳;
- static unsigned long long _lasttimestamp;
- #ifndef USE_C0X
- // 如果不是c++11的话,不能使用atomic;
- std::mutex _mutex;
- #endif
- private:
- unsigned long long next_timestamp();
- public:
- void setWorkerId(const unsigned char &workerId);
- void setDatacenterId(const unsigned char &datacenterId);
- unsigned long long get_unique_id();
- };
|