c++11 雪花算法
时间: 2023-11-24 18:51:54 浏览: 66
雪花算法工具类
以下是C++11实现的雪花算法代码示例:
```c++
#include <iostream>
#include <chrono>
#include <thread>
class Snowflake {
public:
Snowflake(uint16_t worker_id, uint16_t data_center_id) :
worker_id_(worker_id), data_center_id_(data_center_id) {}
uint64_t NextId() {
uint64_t timestamp = TimeGen();
if (timestamp == last_timestamp_) {
sequence_ = (sequence_ + 1) & kSequenceMask;
if (sequence_ == 0) {
timestamp = TilNextMillis(last_timestamp_);
}
} else {
sequence_ = 0;
}
if (timestamp < last_timestamp_) {
throw std::runtime_error("Clock moved backwards");
}
last_timestamp_ = timestamp;
return ((timestamp - kEpoch) << kTimestampLeftShift) |
(data_center_id_ << kDataCenterIdShift) |
(worker_id_ << kWorkerIdShift) |
sequence_;
}
private:
uint64_t TimeGen() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
}
uint64_t TilNextMillis(uint64_t last_timestamp) {
uint64_t timestamp = TimeGen();
while (timestamp <= last_timestamp) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
timestamp = TimeGen();
}
return timestamp;
}
private:
uint16_t worker_id_;
uint16_t data_center_id_;
uint64_t last_timestamp_ = 0;
uint16_t sequence_ = 0;
static constexpr uint64_t kEpoch = 1288834974657;
static constexpr uint64_t kWorkerIdBits = 5;
static constexpr uint64_t kDataCenterIdBits = 5;
static constexpr uint64_t kMaxWorkerId = (1 << kWorkerIdBits) - 1;
static constexpr uint64_t kMaxDataCenterId = (1 << kDataCenterIdBits) - 1;
static constexpr uint64_t kSequenceBits = 12;
static constexpr uint64_t kWorkerIdShift = kSequenceBits;
static constexpr uint64_t kDataCenterIdShift = kSequenceBits + kWorkerIdBits;
static constexpr uint64_t kTimestampLeftShift = kSequenceBits + kWorkerIdBits + kDataCenterIdBits;
static constexpr uint64_t kSequenceMask = (1 << kSequenceBits) - 1;
};
int main() {
Snowflake snowflake(1, 1);
std::cout << snowflake.NextId() << std::endl;
return 0;
}
```
阅读全文