- Notifications
You must be signed in to change notification settings - Fork752
Releasing GIL in long-running C# method causes "Fatal Python error: PyEval_SaveThread: the function must be called with the GIL held, but the GIL is released (the current Python thread state is NULL)"#2209
-
Environment
DetailsI'm trying to prevent a long running method in C# from blocking execution in Python. I followed the guidance onhttps://github.com/pythonnet/pythonnet/wiki/Threading but I am getting a crash.
importpythonnetpythonnet.load('coreclr')importosbin_path=os.path.normpath(os.path.dirname(os.path.abspath(__file__))+"/../LongRunningTask/bin/Debug/netcoreapp3.1")importclrclr.AddReference(os.path.join(bin_path,"LongRunningTask"))clr.AddReference("System")fromLongRunningTaskimportLongRunningTaskfromthreadingimportThread,Timert1=Thread(target=LongRunningTask.Run)t1.daemon=Truet1.start() usingSystem.Threading;usingPython.Runtime;namespaceLongRunningTask{publicclassLongRunningTask{publicstaticvoidRun(){varstate=PythonEngine.BeginAllowThreads();Thread.Sleep(1000);PythonEngine.EndAllowThreads(state);}}}
|
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 2 comments 3 replies
-
When Python calls C# GIL is not held in the first place, so no need to release anything. |
BetaWas this translation helpful?Give feedback.
All reactions
-
I see, thanks. |
BetaWas this translation helpful?Give feedback.
All reactions
-
Hi@lostmsu. I'm confused by your comment:
This seems to contradict this pagehttps://github.com/pythonnet/pythonnet/wiki/Threading which says: "If you are calling C# from Python, and the C# code performs a long-running operation (e.g. computation, I/O, sleep, acquiring a lock, ...), release the GIL via PythonEngine.BeginAllowThreads(). Remember to restore it before returning control to Python" The same question is here:#2424 |
BetaWas this translation helpful?Give feedback.
All reactions
-
This might be confusing. I believe by default now GIL is not held when .NET code is called from Python. So actually in order to work with any Python objects you have to call and hold The wiki is outdated. |
BetaWas this translation helpful?Give feedback.
All reactions
-
Thanks for the clarification |
BetaWas this translation helpful?Give feedback.
All reactions
This discussion was converted from issue #2208 on August 04, 2023 22:07.