1
0
mirror of synced 2025-12-19 03:28:05 +08:00
Files
SnowFlake-IdGenerator/C/source/idgen/SnowWorkerM2.c
2021-06-28 17:22:45 +08:00

31 lines
1.0 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* 版权属于yitter(yitter@126.com)
* 代码翻译amuluowin
* 代码修订yitter
* 开源地址https://github.com/yitter/idgenerator
*/
#include <malloc.h>
#include <stdlib.h>
#include <pthread.h>
#include "SnowWorkerM2.h"
extern uint64_t WorkerM2NextId(SnowFlakeWorker *worker) {
pthread_mutex_lock(&ThreadMutex);
uint64_t currentTimeTick = GetCurrentTimeTick(worker);
if (worker->_LastTimeTick == currentTimeTick) {
worker->_CurrentSeqNumber = (++worker->_CurrentSeqNumber) & worker->MaxSeqNumber;
if (worker->_CurrentSeqNumber == 0) {
currentTimeTick = GetNextTimeTick(worker);
}
} else {
worker->_CurrentSeqNumber = worker->MinSeqNumber;
}
worker->_LastTimeTick = currentTimeTick;
uint64_t id = (uint64_t) ((currentTimeTick << worker->_TimestampShift) |
(worker->WorkerId << worker->SeqBitLength) |
worker->_CurrentSeqNumber);
pthread_mutex_unlock(&ThreadMutex);
return id;
}