Skip to content

Commit

Permalink
Removed lock and implemented SpinWait and Interlocked for enhanced pe…
Browse files Browse the repository at this point in the history
…rformance
  • Loading branch information
hueifeng committed Oct 19, 2023
1 parent b382549 commit 1f04d3a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 18 deletions.
12 changes: 12 additions & 0 deletions Snowflake.Redis.Sample/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"profiles": {
"Snowflake.Redis.Sample": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:57871;http://localhost:57872"
}
}
}
37 changes: 19 additions & 18 deletions Snowflake/SnowFlake.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Threading;

namespace Snowflake
{
Expand Down Expand Up @@ -51,52 +52,52 @@ public SnowFlake(long datacenterId, long machineId)
_machineId = machineId;
}

readonly object _lock = new object();

/// <summary>
/// 产生下一个ID
/// </summary>
/// <returns></returns>
public virtual long NextId()
{
lock (_lock)
while (true)
{
long currStamp = GetNewStamp();

if (currStamp < _lastStamp)
long timestamp = GetNewStamp();
if (timestamp < _lastStamp)
{
//时钟回拨,更新为上一次生成id的时间戳
currStamp = _lastStamp;
//throw new Exception("Clock moved backwards. Refusing to generate id");
timestamp = _lastStamp;
}

if (currStamp == _lastStamp)
if (_lastStamp == timestamp)
{
//相同毫秒内,序列号自增
_sequence = (_sequence + 1) & MaxSequence;
//同一毫秒的序列数已经达到最大
if (_sequence == 0L)
{
currStamp = GetNextMill();
SpinWait.SpinUntil(() => GetNewStamp() > _lastStamp);
continue;
}
}
else
{
//不同毫秒内,序列号置为0
_sequence = 0;
_sequence = 0L;
}

_lastStamp = currStamp;

var id = ((currStamp - StartStamp) << TimestampLeft) //时间戳部分
| (_datacenterId << DatacenterLeft) //数据中心部分
| (_machineId << MachineLeft) //机器标识部分
| _sequence; //序列号部分
if (Interlocked.CompareExchange(ref _lastStamp, timestamp, timestamp) != timestamp)
{
continue;
}

return id;
// Bits for timestamp, data center, machine identifier, and sequence number
return ((timestamp - StartStamp) << TimestampLeft)
| (_datacenterId << DatacenterLeft)
| (_machineId << MachineLeft)
| _sequence;
}
}


protected virtual long GetNextMill()
{
long mill = GetNewStamp();
Expand Down

0 comments on commit 1f04d3a

Please sign in to comment.