验证中...
语言: C/C++
分类: 其他
最后更新于 2018-04-09 10:59
snowflake
原始数据 复制代码
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define unlikely(expr) __builtin_expect(!!(expr), 0)
#define likely(expr) __builtin_expect(!!(expr), 1)
#define SEQ_BITS 12
#define MACHINE_ID_BITS 10
#define TS_LEFT_BITS 22
static uint64_t start_time_stamp = 1420041600000; // 2015-01-01
static uint64_t machine_id_mask = 0x2FF;
static int seq_mask = -1 ^ (-1 << SEQ_BITS);
static uint64_t machine_id;
static uint64_t curr_seq;
static uint64_t last_time_stamp;
static int machine_id_set_flag;
static uint64_t __gen_time_stamp() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64_t)tv.tv_sec * 1000 + (uint64_t)tv.tv_usec / 1000;
}
static void __default_set_machine_id() {
struct ifaddrs *ifap, *ifa;
getifaddrs(&ifap);
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;
if (ifa->ifa_addr->sa_family == AF_INET && strcmp(ifa->ifa_name, "lo")) {
char host[NI_MAXHOST] ={0};
int s;
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (s == 0) {
unsigned int a, b, c, d;
sscanf(host, "%u.%u.%u.%u", &a, &b, &c, &d);
a *= 16777216;
b *= 65536;
c *= 256;
machine_id = (uint64_t)(a + b + c + d);
machine_id &= machine_id_mask;
}
}
}
freeifaddrs(ifap);
}
static uint64_t __waite_next_time_stamp(uint64_t lts) {
uint64_t now = __gen_time_stamp();
while (now <= lts) {
now = __gen_time_stamp();
}
return now;
}
void set_machine_id(uint64_t mid) {
machine_id = mid;
machine_id_set_flag = 1;
}
uint64_t get_next_seq_id() {
uint64_t now = __gen_time_stamp();
if (now < last_time_stamp)
return 0;
if (now == last_time_stamp) {
curr_seq = (curr_seq + 1) & seq_mask;
if (curr_seq == 0)
now = __waite_next_time_stamp(now);
} else {
curr_seq = 0;
}
last_time_stamp = now;
if (unlikely(!machine_id_set_flag)) {
__default_set_machine_id();
machine_id_set_flag = 1;
}
return ((now - start_time_stamp) << TS_LEFT_BITS) | (machine_id << SEQ_BITS) | curr_seq;
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助