Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Increment multithreading issue #207

Open
MarkoPielic opened this issue Dec 19, 2023 · 0 comments
Open

Increment multithreading issue #207

MarkoPielic opened this issue Dec 19, 2023 · 0 comments

Comments

@MarkoPielic
Copy link

MarkoPielic commented Dec 19, 2023

Increment operation should be thread safe and atomic, but it is not - at least not when the key you are trying to increment does not exist.

If you try to do this:

 var result = memcachedClient.Increment(key, 1, 1, TimeSpan.FromDays(2));
 Console.WriteLine("Increment value: " + result);

From the single thread it will work as expected.
But if you try to do it from multiple threads it will sometimes work as expected and sometimes not (roughly about 50-50).

Full program to reproduce the issue (running on .NET 6) is below.

using Enyim.Caching;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
IConfiguration configuration = builder.Build();

var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(configuration);
serviceCollection.AddLogging();
serviceCollection.AddEnyimMemcached();

var serviceProvider = serviceCollection.BuildServiceProvider();
var memcachedClient = serviceProvider.GetService<IMemcachedClient>();

string key = Guid.NewGuid().ToString();
List<Task> tasks = Enumerable.Range(1, 10)
    .Select(item => Task.Run(() =>
    {
        var result = memcachedClient.Increment(key, 1, 1, TimeSpan.FromDays(2));
        Console.WriteLine("Increment value: " + result);
    }))
    .ToList();

await Task.WhenAll(tasks);

var result = await memcachedClient.GetAsync<string>(key);
Console.WriteLine("Final result: " + result.Value);

CURRENT BEHAVIOR

  • increment defaults do 0 or 1 when there is no key (50-50)
  • each subsequent increment increases by 1
  • final result is 9 or 10 (50-50)

EXPECTED BEHAVIOR

  • increment should alawys default to 1 if key does not exist
  • increment should always increment by 1
  • the output of the increment operation should never be 0
  • final result should be 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant