Skip to content

Synchronization in ManualResetValueTaskSourceCore is inconsistent with the memory model #68623

Closed

Description

@nagya

In this implementation, SetResult uses Interlocked.CompareExchange to release the result, but a GetStatus + GetResult, which is typically run concurrently with SetResult, has no synchronization in it, it's just plain non-volatile loads. So an uninitialized or torn _result could be loaded before _continuation and _completed are loaded and observed to be non-null and true respectively.

There also seems to be a similar issue in the case when SetResult is racing against OnCompleted. OnCompleted uses Interlocked.CompareExchange to release _continuation and _continuationState, but if SignalCompletion on line 216 observes _continuation as non-null, it skips the barrier and proceeds to use both _continuation and _continuationState without any synchronization, meaning an uninitialized _continuationState could have been loaded earlier.

Since .NET Core's memory model is not documented (#63474), it's possible it has a property that makes this code correct. In that case please consider this a request to clarify what that property is. My current understanding is that even in the strictest viable memory models, non-volatile loads can be reordered freely.

Activity

  1. ghost added
    untriaged
    on Apr 27, 2022
  2. removed
    untriaged
    on Jul 7, 2022
  3. added this to the Future milestone on Jul 7, 2022
  4. nagya commented on Jul 14, 2022

    @nagya
    Author

    @mangod9, @stephentoub Can you please at least clarify if this would be a threading bug, correct code that relies on an undocumented feature of the memory model, or something else?

  5. stephentoub commented on Jul 15, 2022

    @stephentoub
    Member

    Technically, some of the reads on _continuation should probably be volatile.

  6. ghost added
    in-pr
    on Jul 22, 2022
  7. ghost removed
    in-pr
    on Jul 27, 2022
  8. ghost locked as resolved and limited conversation to collaborators on Aug 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions