@@ -51,6 +51,21 @@ unsafe impl Traverse for Coro {
5151 }
5252}
5353
54+ /// An exclusive claim on a generator's frame, released when dropped.
55+ ///
56+ /// Only the holder may look at the frame or resume it. Resuming decides from
57+ /// the frame state whether the sent value goes on the value stack, so a state
58+ /// read taken before the claim can be answered by a frame that another thread
59+ /// then advances: resuming it leaves the stack short of what the code after
60+ /// the yield pops.
61+ struct RunningGuard < ' a > ( & ' a Coro ) ;
62+
63+ impl Drop for RunningGuard < ' _ > {
64+ fn drop ( & mut self ) {
65+ self . 0 . running . store ( false ) ;
66+ }
67+ }
68+
5469fn gen_name ( jen : & PyObject , vm : & VirtualMachine ) -> & ' static str {
5570 let typ = jen. class ( ) ;
5671 if typ. is ( vm. ctx . types . coroutine_type ) {
@@ -88,10 +103,10 @@ impl Coro {
88103 }
89104 }
90105
91- fn maybe_close ( & self , res : & PyResult < ExecutionResult > , entered_frame : bool ) {
92- if !entered_frame {
93- return ;
94- }
106+ /// Retire the generator if the frame it just ran came to an end. The claim
107+ /// is still held, so a thread waiting for it cannot resume a frame that has
108+ /// already finished.
109+ fn maybe_close ( & self , res : & PyResult < ExecutionResult > , _claim : & RunningGuard < ' _ > ) {
95110 match res {
96111 Ok ( ExecutionResult :: Return ( _) ) | Err ( _) => {
97112 self . closed . store ( true ) ;
@@ -109,45 +124,44 @@ impl Coro {
109124 }
110125 }
111126
112- fn run_with_context < F > (
127+ /// Take the frame for this thread, or report that another thread holds it.
128+ ///
129+ /// What the resume depends on -- whether the generator is closed, and
130+ /// whether it has started -- has to be read from here onwards.
131+ fn claim ( & self , jen : & PyObject , vm : & VirtualMachine ) -> PyResult < RunningGuard < ' _ > > {
132+ if self . running . compare_exchange ( false , true ) . is_err ( ) {
133+ return Err ( vm. new_value_error ( format ! ( "{} already executing" , gen_name( jen, vm) ) ) ) ;
134+ }
135+ Ok ( RunningGuard ( self ) )
136+ }
137+
138+ fn run_claimed < F > (
113139 & self ,
114- jen : & PyObject ,
140+ _claim : & RunningGuard < ' _ > ,
115141 vm : & VirtualMachine ,
116142 func : F ,
117- ) -> ( PyResult < ExecutionResult > , bool )
143+ ) -> PyResult < ExecutionResult >
118144 where
119145 F : FnOnce ( & Py < FrameObject > ) -> PyResult < ExecutionResult > ,
120146 {
121- if self . running . compare_exchange ( false , true ) . is_err ( ) {
122- return (
123- Err ( vm. new_value_error ( format ! ( "{} already executing" , gen_name( jen, vm) ) ) ) ,
124- false ,
125- ) ;
126- }
127-
128- // SAFETY: running.compare_exchange guarantees exclusive access
147+ // SAFETY: the claim guarantees exclusive access
129148 let gen_exc = unsafe { self . exception . swap ( None ) } ;
130149 let exception_ptr = & self . exception as * const PyAtomicRef < Option < PyBaseException > > ;
131150
132- let result = vm. resume_gen_frame ( & self . frame , gen_exc, |f| {
151+ vm. resume_gen_frame ( & self . frame , gen_exc, |f| {
133152 let result = func ( f) ;
134- // SAFETY: exclusive access guaranteed by running flag
153+ // SAFETY: exclusive access guaranteed by the claim
135154 let _old = unsafe { ( * exception_ptr) . swap ( vm. current_exception ( ) ) } ;
136155 result
137- } ) ;
138-
139- self . running . store ( false ) ;
140- ( result, true )
156+ } )
141157 }
142158
143159 fn finalize_send_result (
144160 & self ,
145161 result : PyResult < ExecutionResult > ,
146- entered_frame : bool ,
147162 jen : & PyObject ,
148163 vm : & VirtualMachine ,
149164 ) -> PyResult < PyIterReturn > {
150- self . maybe_close ( & result, entered_frame) ;
151165 match result {
152166 Ok ( exec_res) => Ok ( exec_res. into_iter_return ( vm) ) ,
153167 Err ( e) => {
@@ -177,16 +191,20 @@ impl Coro {
177191 if self . closed . load ( ) {
178192 return Ok ( PyIterReturn :: StopIteration ( None ) ) ;
179193 }
180- if self . running . load ( ) {
181- return Err ( vm. new_value_error ( format ! ( "{} already executing" , gen_name( jen, vm) ) ) ) ;
194+ let claim = self . claim ( jen, vm) ?;
195+ // The generator can have run to its end in the meantime.
196+ if self . closed . load ( ) {
197+ return Ok ( PyIterReturn :: StopIteration ( None ) ) ;
182198 }
183199 let value = if self . frame . lasti ( ) > 0 {
184200 Some ( vm. ctx . none ( ) )
185201 } else {
186202 None
187203 } ;
188- let ( result, entered_frame) = self . run_with_context ( jen, vm, |f| f. resume ( value, vm) ) ;
189- self . finalize_send_result ( result, entered_frame, jen, vm)
204+ let result = self . run_claimed ( & claim, vm, |f| f. resume ( value, vm) ) ;
205+ self . maybe_close ( & result, & claim) ;
206+ drop ( claim) ;
207+ self . finalize_send_result ( result, jen, vm)
190208 }
191209
192210 pub fn send (
@@ -198,8 +216,10 @@ impl Coro {
198216 if self . closed . load ( ) {
199217 return Ok ( PyIterReturn :: StopIteration ( None ) ) ;
200218 }
201- if self . running . load ( ) {
202- return Err ( vm. new_value_error ( format ! ( "{} already executing" , gen_name( jen, vm) ) ) ) ;
219+ let claim = self . claim ( jen, vm) ?;
220+ // The generator can have run to its end in the meantime.
221+ if self . closed . load ( ) {
222+ return Ok ( PyIterReturn :: StopIteration ( None ) ) ;
203223 }
204224 let value = if self . frame . lasti ( ) > 0 {
205225 Some ( value)
@@ -211,8 +231,10 @@ impl Coro {
211231 } else {
212232 None
213233 } ;
214- let ( result, entered_frame) = self . run_with_context ( jen, vm, |f| f. resume ( value, vm) ) ;
215- self . finalize_send_result ( result, entered_frame, jen, vm)
234+ let result = self . run_claimed ( & claim, vm, |f| f. resume ( value, vm) ) ;
235+ self . maybe_close ( & result, & claim) ;
236+ drop ( claim) ;
237+ self . finalize_send_result ( result, jen, vm)
216238 }
217239
218240 pub fn throw (
@@ -237,13 +259,25 @@ impl Coro {
237259 // Validate exception type before entering generator context.
238260 // Invalid types propagate to caller without closing the generator.
239261 crate :: exceptions:: ExceptionCtor :: try_from_object ( vm, exc_type. clone ( ) ) ?;
240- let ( result, entered_frame) =
241- self . run_with_context ( jen, vm, |f| f. gen_throw ( vm, exc_type, exc_val, exc_tb) ) ;
242- self . maybe_close ( & result, entered_frame) ;
262+ let claim = self . claim ( jen, vm) ?;
263+ // The generator can have run to its end in the meantime. Normalizing
264+ // runs the exception's constructor, so let the claim go first.
265+ if self . closed . load ( ) {
266+ drop ( claim) ;
267+ return Err ( vm. normalize_exception ( exc_type, exc_val, exc_tb) ?) ;
268+ }
269+ let result = self . run_claimed ( & claim, vm, |f| f. gen_throw ( vm, exc_type, exc_val, exc_tb) ) ;
270+ self . maybe_close ( & result, & claim) ;
271+ drop ( claim) ;
243272 Ok ( result?. into_iter_return ( vm) )
244273 }
245274
246275 pub fn close ( & self , jen : & PyObject , vm : & VirtualMachine ) -> PyResult < PyObjectRef > {
276+ if self . closed . load ( ) {
277+ return Ok ( vm. ctx . none ( ) ) ;
278+ }
279+ let claim = self . claim ( jen, vm) ?;
280+ // The generator can have run to its end in the meantime.
247281 if self . closed . load ( ) {
248282 return Ok ( vm. ctx . none ( ) ) ;
249283 }
@@ -252,24 +286,19 @@ impl Coro {
252286 self . closed . store ( true ) ;
253287 return Ok ( vm. ctx . none ( ) ) ;
254288 }
255- let ( result, entered_frame ) = self . run_with_context ( jen , vm, |f| {
289+ let result = self . run_claimed ( & claim , vm, |f| {
256290 f. gen_throw (
257291 vm,
258292 vm. ctx . exceptions . generator_exit . to_owned ( ) . into ( ) ,
259293 vm. ctx . none ( ) ,
260294 vm. ctx . none ( ) ,
261295 )
262296 } ) ;
263- if !entered_frame {
264- return match result {
265- Err ( err) => Err ( err) ,
266- Ok ( _) => unreachable ! ( "run_with_context preflight returned without an error" ) ,
267- } ;
268- }
269297 self . closed . store ( true ) ;
270298 // Release frame locals and stack to free references held by the
271299 // closed generator, matching gen_send_ex2 with close_on_completion.
272300 self . clear_frame_locals_on_close ( ) ;
301+ drop ( claim) ;
273302 match result {
274303 Ok ( ExecutionResult :: Yield ( _) ) => {
275304 Err ( vm. new_runtime_error ( format ! ( "{} ignored GeneratorExit" , gen_name( jen, vm) ) ) )
0 commit comments