madelson / DistributedLock

A .NET library for distributed synchronization
MIT License
1.74k stars 182 forks source link

Postgres - Multiple threads successfully acquire the same lock #171

Closed Tom4Real closed 4 months ago

Tom4Real commented 9 months ago

Using DistributedLock.Postgres v1.0.4 with connectionString and new PostgresAdvisoryLockKey("MyLockName", allowHashing: true) - 3 threads each with their own PostgresDistributedLock from the same application intance, all acquired a lock with the same name successfully at the same time.

madelson commented 9 months ago

Thanks for reporting @Tom4Real . Do you have a repro? Any theories as to what is happening? Anything non-default about your Postgres setup (eg pgbouncer)?

Can you show a snippet of your code?

madelson commented 9 months ago

@Tom4Real any update here?

madelson commented 4 months ago
    [Test]
    public async Task Repro()
    {
        var key = new PostgresAdvisoryLockKey("MyLockName", allowHashing: true);
        var conn = TestingPostgresDb.DefaultConnectionString;
        var lock1 = new PostgresDistributedLock(key, conn);
        var lock2 = new PostgresDistributedLock(key, conn);
        var lock3 = new PostgresDistributedLock(key, conn);
        var counter = 0;
        await Task.WhenAll(new[] { lock1, lock2, lock3 }.Select(l => Task.Run(async () =>
        {
            await using (await l.AcquireAsync())
            {
                var c = Interlocked.Increment(ref counter);
                if (c != 1) { throw new Exception("concurrent acquisition!"); }
                await Task.Delay(1000);
                Interlocked.Decrement(ref counter);
            }
        })));
    }

Attempted to reproduce with the above code. It does not repro for me. @Tom4Real please let me know if you're still observing this and can share additional detail. For now I'm closing this as not reproducible.