123456789101112131415161718192021222324252627282930313233343536373839404142 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace fis
- {
- internal interface IKeyLockEngine
- {
- Task InvokeAsync(string key, Func<Task> action);
- }
- internal class SpinLockEngine : IKeyLockEngine
- {
- private const int LockeCount = 0x12fd; //素数,减少hash冲突,值越大冲突概率越小,但占用内存越大
- private static readonly int[] Locks = new int[LockeCount];
- public async Task InvokeAsync(string key, Func<Task> action)
- {
- int index = (key.GetHashCode() & 0x7fffffff) % LockeCount;
- // 尝试0变1,进入对应index的临界状态;
- while (Interlocked.CompareExchange(ref Locks[index], 1, 0) == 1)
- {
- Thread.Sleep(1);
- ////可也以计数方式.每X次尝试失败则睡眠1,否则睡眠0
- //Thread.Sleep(((++count) | 0x000f) == 0 ? 1 : 0);
- }
- try
- {
- await action();
- }
- finally
- {
- Thread.VolatileWrite(ref Locks[index], 0);
- }
- }
- }
- }
|