11use std:: num:: NonZero ;
22use std:: sync:: atomic:: { AtomicBool , AtomicUsize , Ordering } ;
3+ use std:: sync:: { Condvar , Mutex } ;
34use tracing:: warn;
45
56/// Number of extraction threads, from `CODEQL_THREADS` (set by the CLI from `--threads`).
@@ -39,6 +40,42 @@ impl Drop for AbortOnPanic<'_> {
3940 }
4041}
4142
43+ /// Calls `run` on `threads` threads, each with its own result of `init` (called on the current
44+ /// thread), returning the results. If `inline`, a single state runs on the current thread instead.
45+ /// If a thread panics, the panic is propagated once all threads have finished. If a thread cannot
46+ /// be spawned, `stop` is called to make the already spawned ones finish early before panicking.
47+ fn run_on_threads < I : Send , O : Send > (
48+ inline : bool ,
49+ threads : usize ,
50+ mut init : impl FnMut ( ) -> I ,
51+ run : impl Fn ( I ) -> O + Sync ,
52+ stop : impl Fn ( ) ,
53+ ) -> Vec < O > {
54+ if inline {
55+ return vec ! [ run( init( ) ) ] ;
56+ }
57+ let states: Vec < _ > = ( 0 ..threads) . map ( |_| init ( ) ) . collect ( ) ;
58+ std:: thread:: scope ( |scope| {
59+ let handles: Vec < _ > = states
60+ . into_iter ( )
61+ . map ( |state| {
62+ std:: thread:: Builder :: new ( )
63+ . stack_size ( WORKER_STACK_SIZE )
64+ . spawn_scoped ( scope, || run ( state) )
65+ . unwrap_or_else ( |e| {
66+ stop ( ) ;
67+ panic ! ( "spawning extraction thread: {e}" )
68+ } )
69+ } )
70+ . collect ( ) ;
71+ let joined: Vec < _ > = handles. into_iter ( ) . map ( |h| h. join ( ) ) . collect ( ) ;
72+ joined
73+ . into_iter ( )
74+ . map ( |r| r. unwrap_or_else ( |e| std:: panic:: resume_unwind ( e) ) )
75+ . collect ( )
76+ } )
77+ }
78+
4279/// Processes `items` on up to `threads` threads pulling from a shared queue.
4380///
4481/// For each thread, `init` is called on the current thread and its result is moved to that
@@ -52,7 +89,7 @@ impl Drop for AbortOnPanic<'_> {
5289pub fn parallel_map < T , I , S , R > (
5390 threads : usize ,
5491 items : & [ T ] ,
55- mut init : impl FnMut ( ) -> I ,
92+ init : impl FnMut ( ) -> I ,
5693 worker : impl Fn ( I , & mut dyn FnMut ( & mut dyn FnMut ( & T ) -> R ) ) -> S + Sync ,
5794) -> ( Vec < S > , Vec < R > )
5895where
@@ -77,30 +114,9 @@ where
77114 } ) ;
78115 ( ret, results)
79116 } ;
80- let outputs = if inline {
81- vec ! [ run( init( ) ) ]
82- } else {
83- let states: Vec < _ > = ( 0 ..threads) . map ( |_| init ( ) ) . collect ( ) ;
84- std:: thread:: scope ( |scope| {
85- let handles: Vec < _ > = states
86- . into_iter ( )
87- . map ( |state| {
88- std:: thread:: Builder :: new ( )
89- . stack_size ( WORKER_STACK_SIZE )
90- . spawn_scoped ( scope, || run ( state) )
91- . unwrap_or_else ( |e| {
92- abort. store ( true , Ordering :: Relaxed ) ;
93- panic ! ( "spawning extraction thread: {e}" )
94- } )
95- } )
96- . collect ( ) ;
97- let joined: Vec < _ > = handles. into_iter ( ) . map ( |h| h. join ( ) ) . collect ( ) ;
98- joined
99- . into_iter ( )
100- . map ( |r| r. unwrap_or_else ( |e| std:: panic:: resume_unwind ( e) ) )
101- . collect :: < Vec < _ > > ( )
102- } )
103- } ;
117+ let outputs = run_on_threads ( inline, threads, init, run, || {
118+ abort. store ( true , Ordering :: Relaxed ) ;
119+ } ) ;
104120 let mut states = Vec :: with_capacity ( outputs. len ( ) ) ;
105121 let mut results = Vec :: with_capacity ( items. len ( ) ) ;
106122 for ( state, worker_results) in outputs {
@@ -112,6 +128,105 @@ where
112128 ( states, results. into_iter ( ) . map ( |( _, r) | r) . collect ( ) )
113129}
114130
131+ struct Schedule {
132+ ready : Vec < usize > ,
133+ missing_deps : Vec < usize > ,
134+ running : usize ,
135+ abort : bool ,
136+ }
137+
138+ /// Marks a node as finished when dropped, releasing its dependents unless unwinding.
139+ struct Finish < ' a > {
140+ node : usize ,
141+ schedule : & ' a Mutex < Schedule > ,
142+ wakeup : & ' a Condvar ,
143+ dependents : & ' a [ Vec < usize > ] ,
144+ }
145+
146+ impl Drop for Finish < ' _ > {
147+ fn drop ( & mut self ) {
148+ let mut schedule = self . schedule . lock ( ) . unwrap ( ) ;
149+ schedule. running -= 1 ;
150+ if std:: thread:: panicking ( ) {
151+ schedule. abort = true ;
152+ } else {
153+ for & dependent in & self . dependents [ self . node ] {
154+ schedule. missing_deps [ dependent] -= 1 ;
155+ if schedule. missing_deps [ dependent] == 0 {
156+ schedule. ready . push ( dependent) ;
157+ }
158+ }
159+ }
160+ self . wakeup . notify_all ( ) ;
161+ }
162+ }
163+
164+ /// Calls `work` on each node of a dependency graph on up to `threads` threads, only once all
165+ /// dependencies of that node have completed. `deps[i]` lists the nodes `i` depends on, and nodes
166+ /// on or depending on a cycle are skipped. `init` is called on the current thread for each thread.
167+ ///
168+ /// If `work` panics, the other threads stop starting nodes and the panic is propagated once they
169+ /// finish.
170+ pub fn for_each_in_dependency_order < I : Send > (
171+ threads : usize ,
172+ deps : & [ Vec < usize > ] ,
173+ init : impl FnMut ( ) -> I ,
174+ work : impl Fn ( & mut I , usize ) + Sync ,
175+ ) {
176+ let mut dependents = vec ! [ Vec :: new( ) ; deps. len( ) ] ;
177+ for ( node, node_deps) in deps. iter ( ) . enumerate ( ) {
178+ for & dep in node_deps {
179+ dependents[ dep] . push ( node) ;
180+ }
181+ }
182+ let missing_deps: Vec < _ > = deps. iter ( ) . map ( Vec :: len) . collect ( ) ;
183+ let ready = ( 0 ..deps. len ( ) ) . filter ( |& i| missing_deps[ i] == 0 ) . collect ( ) ;
184+ let schedule = Mutex :: new ( Schedule {
185+ ready,
186+ missing_deps,
187+ running : 0 ,
188+ abort : false ,
189+ } ) ;
190+ let wakeup = Condvar :: new ( ) ;
191+ let run = |mut state : I | {
192+ loop {
193+ let node = {
194+ let mut schedule = schedule. lock ( ) . unwrap ( ) ;
195+ loop {
196+ if schedule. abort {
197+ return ;
198+ }
199+ if let Some ( node) = schedule. ready . pop ( ) {
200+ schedule. running += 1 ;
201+ break node;
202+ }
203+ if schedule. running == 0 {
204+ return ;
205+ }
206+ schedule = wakeup. wait ( schedule) . unwrap ( ) ;
207+ }
208+ } ;
209+ let _finish = Finish {
210+ node,
211+ schedule : & schedule,
212+ wakeup : & wakeup,
213+ dependents : & dependents,
214+ } ;
215+ work ( & mut state, node) ;
216+ }
217+ } ;
218+ run_on_threads (
219+ threads <= 1 ,
220+ threads. clamp ( 1 , deps. len ( ) . max ( 1 ) ) ,
221+ init,
222+ run,
223+ || {
224+ schedule. lock ( ) . unwrap ( ) . abort = true ;
225+ wakeup. notify_all ( ) ;
226+ } ,
227+ ) ;
228+ }
229+
115230#[ cfg( test) ]
116231mod tests {
117232 use super :: * ;
@@ -229,4 +344,108 @@ mod tests {
229344 assert_eq ! ( results. len( ) , items. len( ) ) ;
230345 }
231346 }
347+
348+ fn run_graph ( threads : usize , deps : & [ Vec < usize > ] ) -> Vec < usize > {
349+ let done: Vec < _ > = deps. iter ( ) . map ( |_| AtomicBool :: new ( false ) ) . collect ( ) ;
350+ let order = Mutex :: new ( Vec :: new ( ) ) ;
351+ let ( running, max_running) = ( AtomicUsize :: new ( 0 ) , AtomicUsize :: new ( 0 ) ) ;
352+ for_each_in_dependency_order (
353+ threads,
354+ deps,
355+ || ( ) ,
356+ |( ) , node| {
357+ let now = running. fetch_add ( 1 , Ordering :: SeqCst ) + 1 ;
358+ max_running. fetch_max ( now, Ordering :: SeqCst ) ;
359+ assert ! ( deps[ node] . iter( ) . all( |& d| done[ d] . load( Ordering :: SeqCst ) ) ) ;
360+ std:: thread:: sleep ( std:: time:: Duration :: from_millis ( 1 ) ) ;
361+ done[ node] . store ( true , Ordering :: SeqCst ) ;
362+ order. lock ( ) . unwrap ( ) . push ( node) ;
363+ running. fetch_sub ( 1 , Ordering :: SeqCst ) ;
364+ } ,
365+ ) ;
366+ assert ! ( max_running. into_inner( ) <= threads. max( 1 ) ) ;
367+ order. into_inner ( ) . unwrap ( )
368+ }
369+
370+ #[ test]
371+ fn dependency_order_is_respected ( ) {
372+ // a diamond on top of independent chains
373+ let mut deps = vec ! [ vec![ ] , vec![ 0 ] , vec![ 0 ] , vec![ 1 , 2 ] ] ;
374+ for i in 4 ..40 {
375+ deps. push ( if i % 4 == 0 { vec ! [ ] } else { vec ! [ i - 1 , 3 ] } ) ;
376+ }
377+ for threads in [ 1 , 2 , 8 ] {
378+ let mut order = run_graph ( threads, & deps) ;
379+ order. sort_unstable ( ) ;
380+ assert_eq ! ( order, ( 0 ..deps. len( ) ) . collect:: <Vec <_>>( ) ) ;
381+ }
382+ }
383+
384+ #[ test]
385+ fn empty_graph_terminates ( ) {
386+ assert_eq ! ( run_graph( 4 , & [ ] ) , Vec :: <usize >:: new( ) ) ;
387+ }
388+
389+ #[ test]
390+ fn cycles_are_skipped ( ) {
391+ let deps = [ vec ! [ 1 ] , vec ! [ 0 ] , vec ! [ 1 ] , vec ! [ ] , vec ! [ 3 ] , vec ! [ 5 ] ] ;
392+ for threads in [ 1 , 4 ] {
393+ let mut order = run_graph ( threads, & deps) ;
394+ order. sort_unstable ( ) ;
395+ assert_eq ! ( order, [ 3 , 4 ] ) ;
396+ }
397+ }
398+
399+ #[ test]
400+ fn dependency_order_panic_propagates ( ) {
401+ // `49` is started first, and the other ready nodes are queued behind it
402+ let deps: Vec < _ > = ( 0 ..100 )
403+ . map ( |i| if i < 50 { vec ! [ ] } else { vec ! [ 49 ] } )
404+ . collect ( ) ;
405+ let started = AtomicUsize :: new ( 0 ) ;
406+ let panicking = AtomicBool :: new ( false ) ;
407+ let result = std:: panic:: catch_unwind ( || {
408+ for_each_in_dependency_order (
409+ 2 ,
410+ & deps,
411+ || ( ) ,
412+ |( ) , node| {
413+ started. fetch_add ( 1 , Ordering :: SeqCst ) ;
414+ if node == 49 {
415+ panicking. store ( true , Ordering :: SeqCst ) ;
416+ std:: panic:: panic_any ( node) ;
417+ }
418+ // give the panic time to reach the scheduler
419+ while !panicking. load ( Ordering :: SeqCst ) {
420+ std:: thread:: yield_now ( ) ;
421+ }
422+ std:: thread:: sleep ( std:: time:: Duration :: from_millis ( 200 ) ) ;
423+ } ,
424+ ) ;
425+ } ) ;
426+ assert_eq ! ( * result. unwrap_err( ) . downcast:: <usize >( ) . unwrap( ) , 49 ) ;
427+ // after the panic no queued node or dependent is started
428+ assert ! ( started. into_inner( ) <= 2 ) ;
429+ }
430+
431+ #[ test]
432+ fn dependency_order_runs_in_parallel ( ) {
433+ let arrived = AtomicUsize :: new ( 0 ) ;
434+ let deadline = std:: time:: Instant :: now ( ) + std:: time:: Duration :: from_secs ( 10 ) ;
435+ for_each_in_dependency_order (
436+ 2 ,
437+ & [ vec ! [ ] , vec ! [ ] ] ,
438+ || ( ) ,
439+ |( ) , _| {
440+ arrived. fetch_add ( 1 , Ordering :: SeqCst ) ;
441+ while arrived. load ( Ordering :: SeqCst ) < 2 {
442+ assert ! (
443+ std:: time:: Instant :: now( ) < deadline,
444+ "nodes did not overlap"
445+ ) ;
446+ std:: thread:: yield_now ( ) ;
447+ }
448+ } ,
449+ ) ;
450+ }
232451}
0 commit comments