Skip to content

Commit 3362cf8

Browse files
authored
GILState.Dispose is safe to be called multiple times (#1037)
* GILState.Dispose is safe to be called multiple times * test multiple class to GILState.Dispose
1 parent 3b938a5 commit 3362cf8

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/embed_tests/TestGILState.cs

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
namespace Python.EmbeddingTest
2+
{
3+
using NUnit.Framework;
4+
using Python.Runtime;
5+
6+
public class TestGILState
7+
{
8+
/// <summary>
9+
/// Ensure, that calling <see cref="Py.GILState.Dispose"/> multiple times is safe
10+
/// </summary>
11+
[Test]
12+
public void CanDisposeMultipleTimes()
13+
{
14+
using (var gilState = Py.GIL())
15+
{
16+
for(int i = 0; i < 50; i++)
17+
gilState.Dispose();
18+
}
19+
}
20+
}
21+
}

src/runtime/pythonengine.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,8 @@ public static PyScope CreateScope(string name)
643643

644644
public class GILState : IDisposable
645645
{
646-
private IntPtr state;
646+
private readonly IntPtr state;
647+
private bool isDisposed;
647648

648649
internal GILState()
649650
{
@@ -652,8 +653,11 @@ internal GILState()
652653

653654
public void Dispose()
654655
{
656+
if (this.isDisposed) return;
657+
655658
PythonEngine.ReleaseLock(state);
656659
GC.SuppressFinalize(this);
660+
this.isDisposed = true;
657661
}
658662

659663
~GILState()

0 commit comments

Comments
 (0)