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

Fix race condition with Promise.New #482

Merged
merged 1 commit into from
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions Package/Core/Promises/Internal/DeferredInternal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,14 @@ private DeferredNewPromise() { }

internal override void MaybeDispose()
{
Dispose();
ObjectPool.MaybeRepool(this);
// It is theoretically possible for this to be completed from the callback, and then the callback throws,
// causing this to attempt to complete again. The thread could be starved while another thread
// re-uses this object from the pool. This interlocked operation protects against that.
if (InterlockedAddWithUnsignedOverflowCheck(ref _disposeCounter, -1) == 0)
{
Dispose();
ObjectPool.MaybeRepool(this);
}
}

[MethodImpl(InlineOption)]
Expand All @@ -166,6 +172,7 @@ internal static DeferredNewPromise<TResult, TDelegate> GetOrCreate(TDelegate run
{
var promise = GetOrCreate();
promise.Reset();
promise._disposeCounter = 2;
promise._runner = runner;
return promise;
}
Expand Down Expand Up @@ -253,6 +260,7 @@ private void Run()
}
}
ClearCurrentInvoker();
MaybeDispose();
}
}
} // class PromiseRef
Expand Down
1 change: 1 addition & 0 deletions Package/Core/Promises/Internal/PromiseFieldsInternal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ partial class DeferredPromise<TResult> : DeferredPromiseBase<TResult>
partial class DeferredNewPromise<TResult, TDelegate> : DeferredPromise<TResult>
where TDelegate : IDelegateNew<TResult>
{
private int _disposeCounter;
private TDelegate _runner;
}

Expand Down
Loading