Skip to content

Commit 4ec45d0

Browse files
committed
Make sure that initializePython is idempotent
1 parent 4b931d4 commit 4ec45d0

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

src/Python/Internal/Eval.hs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,17 @@ initializePython :: IO ()
157157
-- See NOTE: [Python and threading]
158158
initializePython
159159
| rtsSupportsBoundThreads = runInBoundThread $ mask_ $ do
160-
doInializePython
161-
-- We need to release GIL. Thread calling this will be
162-
-- designated as main will probably never make any progress.
163-
-- We'll never restore thread state
164-
[CU.exp| void { PyEval_SaveThread() } |]
165-
| otherwise = mask_ doInializePython
160+
-- In multithreaded RTS we need to release GIL so other threads
161+
-- may take it.
162+
[CU.exp| int { Py_IsInitialized() } |] >>= \case
163+
0 -> do doInializePython
164+
[CU.exp| void { PyEval_SaveThread() } |]
165+
_ -> pure ()
166+
| otherwise = mask_ $
167+
[CU.exp| int { Py_IsInitialized() } |] >>= \case
168+
0 -> do doInializePython
169+
[CU.exp| void { PyEval_SaveThread() } |]
170+
_ -> pure ()
166171

167172
-- | Destroy python interpreter.
168173
finalizePython :: IO ()
@@ -194,10 +199,6 @@ doInializePython = do
194199
p_argv <- traverse (ContT . withWCString) argv
195200
ptr_argv <- ContT $ withArray (p_argv0 : p_argv)
196201
liftIO [C.block| int {
197-
// Noop is interpreter is already initialized
198-
if( Py_IsInitialized() ) {
199-
return 0;
200-
}
201202
// Now fill config
202203
PyStatus status;
203204
PyConfig cfg;

test/TST/Run.hs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@ module TST.Run(tests) where
55
import Control.Monad
66
import Test.Tasty
77
import Test.Tasty.HUnit
8+
import Python.Inline
89
import Python.Inline.QQ
910
import TST.Util
1011

1112
tests :: TestTree
1213
tests = testGroup "Run python"
1314
[ testCase "Empty QQ" [py_| |]
15+
, testCase "Second init is noop" initializePython
1416
, testCase "Python exceptions are converted" $ throwsPy [py_| 1 / 0 |]
1517
, testCase "Scope pymain->any" $ do
1618
[pymain|

0 commit comments

Comments
 (0)