@@ -110,39 +110,43 @@ def _exec(self, script):
110
110
def initialize (self ):
111
111
assert self .interpid is None , self .interpid
112
112
self .interpid = _interpreters .create (reqrefs = True )
113
- # This may raise InterpreterNotFoundError:
114
- _interpreters .incref (self .interpid )
115
-
116
- maxsize = 0
117
- fmt = 0
118
- self .resultsid = _interpqueues .create (maxsize , fmt , UNBOUND )
119
-
120
- initscript = f"""if True:
121
- from { __name__ } import WorkerContext
122
- """
123
- initscript += LINESEP + self .initscript
124
- # for i, line in enumerate(initscript.splitlines(), 1):
125
- # print(f'{i:>3} {line}')
126
- self ._exec (initscript )
127
- if self .shared :
128
- _interpreters .set___main___attrs (
129
- self .interpid , self .shared , restrict = True )
113
+ try :
114
+ _interpreters .incref (self .interpid )
115
+
116
+ initscript = f"""if True:
117
+ from { __name__ } import WorkerContext
118
+ """
119
+ initscript += LINESEP + self .initscript
120
+ self ._exec (initscript )
121
+
122
+ if self .shared :
123
+ _interpreters .set___main___attrs (
124
+ self .interpid , self .shared , restrict = True )
125
+
126
+ maxsize = 0
127
+ fmt = 0
128
+ self .resultsid = _interpqueues .create (maxsize , fmt , UNBOUND )
129
+ except _interpreters .InterpreterNotFoundError :
130
+ raise # re-raise
131
+ except BaseException :
132
+ self .finalize ()
133
+ raise # re-raise
130
134
131
135
def finalize (self ):
132
136
interpid = self .interpid
133
137
resultsid = self .resultsid
134
138
self .resultsid = None
135
139
self .interpid = None
136
- assert interpid is not None
137
- assert resultsid is not None
138
- try :
139
- _interpqueues .destroy ( resultsid )
140
- except _interpqueues . QueueNotFoundError :
141
- pass
142
- try :
143
- _interpreters .decref (interpid )
144
- except _interpreters .InterpreterNotFoundError :
145
- pass
140
+ if resultsid is not None :
141
+ try :
142
+ _interpqueues . destroy ( resultsid )
143
+ except _interpqueues .QueueNotFoundError :
144
+ pass
145
+ if interpid is not None :
146
+ try :
147
+ _interpreters .decref (interpid )
148
+ except _interpreters .InterpreterNotFoundError :
149
+ pass
146
150
147
151
def run (self , task ):
148
152
data , kind = task
0 commit comments