@@ -216,6 +216,12 @@ private static final class AtExitHook {
216216 /* for fast access to the PythonThreadState object by the owning thread */
217217 private final ContextThreadLocal <PythonThreadState > threadState ;
218218
219+ /*
220+ * Workaround for GR-30072 - we cannot use the threadState above during native image build time,
221+ * so we use a temporary one just for the build
222+ */
223+ private final PythonThreadState buildThreadState ;
224+
219225 /* map of thread IDs to indices for array 'threadStates' */
220226 private Map <Thread , PythonThreadState > threadStateMapping = Collections .synchronizedMap (new WeakHashMap <>());
221227
@@ -257,6 +263,11 @@ private static final class AtExitHook {
257263
258264 public PythonContext (PythonLanguage language , TruffleLanguage .Env env , Python3Core core , ContextThreadLocal <PythonThreadState > threadState ) {
259265 this .language = language ;
266+ if (ImageInfo .inImageBuildtimeCode ()) {
267+ this .buildThreadState = new PythonThreadState (this , Thread .currentThread ());
268+ } else {
269+ this .buildThreadState = null ;
270+ }
260271 this .threadState = threadState ;
261272 this .core = core ;
262273 this .env = env ;
@@ -978,7 +989,7 @@ void acquireGil() {
978989 try {
979990 globalInterpreterLock .lockInterruptibly ();
980991 } catch (InterruptedException e ) {
981- if (threadState .get ().isShuttingDown ()) {
992+ if (! ImageInfo . inImageBuildtimeCode () && threadState .get ().isShuttingDown ()) {
982993 // This is a thread being killed during normal context shutdown. This thread
983994 // should exit now. This should usually only happen for daemon threads on
984995 // context shutdown. This is the equivalent to the logic in pylifecycle.c and
@@ -1096,7 +1107,7 @@ public Thread[] getThreads() {
10961107 }
10971108
10981109 private PythonThreadState getThreadState () {
1099- PythonThreadState curThreadState = threadState . get ();
1110+ PythonThreadState curThreadState = getThreadStateInternal ();
11001111 if (curThreadState .isShuttingDown ()) {
11011112 // we're shutting down, just release and die
11021113 if (ownsGil ()) {
@@ -1107,9 +1118,17 @@ private PythonThreadState getThreadState() {
11071118 return curThreadState ;
11081119 }
11091120
1121+ private PythonThreadState getThreadStateInternal () {
1122+ if (ImageInfo .inImageBuildtimeCode ()) {
1123+ return buildThreadState ;
1124+ } else {
1125+ return threadState .get ();
1126+ }
1127+ }
1128+
11101129 private void applyToAllThreadStates (Consumer <PythonThreadState > action ) {
11111130 if (language .singleThreadedAssumption .isValid ()) {
1112- action .accept (threadState . get ());
1131+ action .accept (getThreadStateInternal ());
11131132 } else {
11141133 synchronized (this ) {
11151134 for (PythonThreadState ts : threadStateMapping .values ()) {
0 commit comments