Skip to content

Incorrect and unexpected optimizer behavior for Interlocked.Exchange with short value #7810

Closed

Description

@stefan-schweiger

NOTE: Most likely this does not just affect Interlocked.Exchange, but it's easy to reproduce this way.

When turning on the optimization for the following code you get different (and also wrong) output values than from building the application without turning on the optimizer.

using System;
using System.Threading;

class Program
{
    private static int _intToExchange = -1;
    private static short _innerShort = 2;

    static void Main( string[] args )
    {
        var oldValue = Interlocked.Exchange(ref _intToExchange, _innerShort);
        Console.WriteLine( "It was:   {0}", oldValue );
        Console.WriteLine( "It is:    {0}", _intToExchange );
        Console.WriteLine( "Expected: {0}", _innerShort );
    }
}

Without using optimization the output is as expected:

It was:   -1
It is:    2
Expected: 2

But when you turn on optimization (e.g. with <Optimize>true</Optimize> in .csproj) this is the output:

It was:   65535
It is:    -65534
Expected: 2

More about this bug can also be found here on stackoverflow.

Activity

  1. mikedn commented on Apr 5, 2017

    @mikedn
    Contributor

    Most likely this does not just affect Interlocked.Exchange, but it's easy to reproduce this way.

    As far as I can tell this affects Interlocked.Add and Interlocked.Exchange. Do you have other examples?

  2. stefan-schweiger commented on Apr 5, 2017

    @stefan-schweiger
    Author

    I don't have any other examples, it was just my best guess that this would probably also affect other methods with similar signatures or internals.

  3. transferred this issue fromdotnet/coreclron Jan 31, 2020
  4. ghost locked as resolved and limited conversation to collaborators on Dec 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions