Skip to content

Instantly share code, notes, and snippets.

@whiler
Created December 29, 2016 06:47
Show Gist options
  • Save whiler/a9c5208b6258ee97140eb7c3e615c5c2 to your computer and use it in GitHub Desktop.
Save whiler/a9c5208b6258ee97140eb7c3e615c5c2 to your computer and use it in GitHub Desktop.
A simple implementation of twitter snowflake in C
#include<time.h>
#include<unistd.h>
/*
* snowflake.c
*
* a simple implementation of twitter snowflake in C
*
* [email protected]
*/
#define BITS 8
#define SEQ 256
unsigned long last = 0;
unsigned char seq = 0;
unsigned long milliseconds();
unsigned long generate();
unsigned long milliseconds() {
struct timespec spec = {0};
clock_gettime(CLOCK_REALTIME, &spec);
return spec.tv_sec * 1000 + spec.tv_nsec / 1000000;
}
unsigned long generate() {
unsigned long current = 0;
while (last > (current = milliseconds())) {
usleep(1000);
}
if (last != current) {
seq = 0;
} else {
seq = (seq + 1) % SEQ;
if (0 == seq) {
while (last >= (current = milliseconds())) {
usleep(1);
}
}
}
last = current;
return (current << BITS) + seq;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment