dotnet / dotnet/runtime

[API Proposal]: Interlocked.Max, Interlocked.Min

Open
#121,264 6 comments 1 reaction 0 assignees View on GitHub
api-suggestion area-System.Threading
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

Some platforms have instructions for atomic fetch max/min.
Languages such as Rust or C++ added these primitives.
This can be useful for .NET to expose these primivites as well.

https://en.cppreference.com/w/cpp/atomic/atomic/fetch_max.html
https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI64.html

### API Proposal

```csharp
public static class Interlocked
{
///
/// Atomically replaces the value at location with the maximum of the current value and the specified value.
/// Returns the original value before the operation.
///
public static int Max(ref int location, int value);

///
/// Atomically replaces the value at location with the minimum of the current value and the specified value.
/// Returns the original value before the operation.
///
public static int Min(ref int location, int value);
}
```

### API Usage

```csharp
int currentMax = 0;

// Thread A
Interlocked.Max(ref currentMax, 42);

// Thread B
int old = Interlocked.Max(ref currentMax, 35);
// If currentMax was 0, after this it will be 42 (because 42 > 35),
// and old will have been 0.

Interlocked.Min(ref currentMax, 10);
// Now currentMax becomes 10 if 10 < 42.
```

### Alternative Designs

_No response_

### Risks

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.