Created
September 22, 2021 15:14
-
-
Save frodo821/ebb2b5c936d5ff615945697fb129249e to your computer and use it in GitHub Desktop.
snowflake identifier generator implementation by python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import time_ns | |
from threading import Lock | |
class SnowflakeGenerator: | |
def __init__(self, instance_id, epoch=-1): | |
self.instance_id = (instance_id&1023)<<12 | |
self.epoch = (time_ns()//1000 & 2199023255551) if epoch == -1 else epoch | |
self.seq = 0 | |
self.last_timestamp = 0 | |
self.lock = Lock() | |
def __call__(self): | |
with self.lock: | |
ts = (time_ns()//1000 & 2199023255551)<<22 | |
if ts == self.last_timestamp: | |
self.seq = (self.seq+1)&4095 | |
if self.seq == 0: | |
ts = self.wait_for_next_millis() | |
else: | |
self.seq == 0 | |
self.last_timestamp = ts | |
return ts + self.instance_id + self.seq | |
def wait_for_next_millis(self): | |
while (t := (time_ns()//1000 & 2199023255551)<<22) == self.last_timestamp: | |
pass | |
return t |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment