Turn from: http://blog.csdn.net/wallwind/article/details/49701397
Before someone asked me to design a distributed incremental unique ID generation. Think for a long time do not know, occasionally a colleague said Snowflake algorithm, I Baidu a bit, very simple and efficient.
Reference
Https://github.com/twitter/snowflake
So, I use C language casually realized a bit, has not reached the industrial level, the need for refinement, but the basic can be used, on the code.
[CPP] View plain copy/* snowflake ID generation strategy millisecond time 41-bit + machine id 10 bit + millisecond inner sequence 12 bits. 0 41 51 64 +-----------+------+------+&NBSP;|TIME&NBSP;|PC |inc | +-----------+------+------+ 41bits is a timestamp in microseconds. then 10bits is a pre-configured machine ID. The last 12bits is the cumulative counter. macheine id (10bits) indicates that up to 1024 machines can produce id,sequence number at the same time (12bits) It also indicates that up to 4,096 id, * attention points are generated in the 1 machine 1ms, because it requires 64-bit operating systems to use the displacement operation, Otherwise the generated ID may be incorrect */ #include <stdio.h> #include < pthread.h> #include <unistd.h> #include <stdlib.h> # include <sched.h> #include <linux/unistd.h> #include <sys/syscall.h> #include <errno.h> #include <linux/types.h> #include <time.h> #include < stdint.h> #include <sys/time.h> struct globle { int global_int:12; uint64_t last_stamp; int workid; int seqid; }; void set_workid (int workid); pid_t gettid ( void ); Uint64_t get_curr_ms (); Uint64_t wait_next_ms ( Uint64_t laststamp); int atomic_incr (int id); uint64_t get_unique_id ();
[CPP]View plain copy #include "snowflake.h" struct globle g_info; #define Sequencemask ( -1l ^ ( -1l << 12L)) void set_workid (int workid)