Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Fix memory leak in finalizer #836

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

Merged
Merged
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
50 changes: 30 additions & 20 deletions src/runtime/finalizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ struct PendingArgs
private ConcurrentQueue<IPyDisposable> _objQueue = new ConcurrentQueue<IPyDisposable>();
private bool _pending = false;
private readonly object _collectingLock = new object();
private IntPtr _pendingArgs;
private IntPtr _pendingArgs = IntPtr.Zero;

#region FINALIZER_CHECK

Expand Down Expand Up @@ -128,7 +128,7 @@ internal void AddFinalizedObject(IPyDisposable obj)
_objQueue.Enqueue(obj);
}
GC.ReRegisterForFinalize(obj);
if (_objQueue.Count >= Threshold)
if (!_pending && _objQueue.Count >= Threshold)
{
AddPendingCollect();
}
Expand Down Expand Up @@ -164,26 +164,28 @@ internal static void Shutdown()

private void AddPendingCollect()
{
if (_pending)
if(Monitor.TryEnter(_collectingLock))
{
return;
}
lock (_collectingLock)
{
if (_pending)
try
{
return;
if (!_pending)
{
_pending = true;
var args = new PendingArgs { cancelled = false };
_pendingArgs = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PendingArgs)));
Marshal.StructureToPtr(args, _pendingArgs, false);
IntPtr func = Marshal.GetFunctionPointerForDelegate(_collectAction);
if (Runtime.Py_AddPendingCall(func, _pendingArgs) != 0)
{
// Full queue, append next time
FreePendingArgs();
_pending = false;
}
}
}
_pending = true;
var args = new PendingArgs() { cancelled = false };
IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PendingArgs)));
Marshal.StructureToPtr(args, p, false);
_pendingArgs = p;
IntPtr func = Marshal.GetFunctionPointerForDelegate(_collectAction);
if (Runtime.Py_AddPendingCall(func, p) != 0)
finally
{
// Full queue, append next time
_pending = false;
Monitor.Exit(_collectingLock);
}
}
}
Expand All @@ -205,8 +207,8 @@ private static int OnPendingCollect(IntPtr arg)
}
finally
{
Instance.FreePendingArgs();
Instance.ResetPending();
Marshal.FreeHGlobal(arg);
}
return 0;
}
Expand Down Expand Up @@ -244,12 +246,20 @@ private void DisposeAll()
}
}

private void FreePendingArgs()
{
if (_pendingArgs != IntPtr.Zero)
{
Marshal.FreeHGlobal(_pendingArgs);
_pendingArgs = IntPtr.Zero;
}
}

private void ResetPending()
{
lock (_collectingLock)
{
_pending = false;
_pendingArgs = IntPtr.Zero;
}
}

Expand Down