Best way to get the result of a crossbeam::scoped-Thread?


#1

Consider the following scenario: I want to work on a big data structure in a concurrent way and use one scoped Thread from the crossbeam-crate. The result of the thread’s computation is returned by the ScopedJoinHandler of the thread and can be extracted by the join()-method.

Problem: outside of the crossbeam-scope I cant use the result anymore. I tried to pre-initialize the variable for the ScopedJoinHandle outside the crossbeam-scope, but there is no new()-Method. Another way would be to use a channel but it seems over-complicated to me when the result is already in the ScopedJoinHandler.

Here is some (pseude)-code:

fn work_on(&[i32]) -> i32 {
    some_work();
}

fn threaded_function() {    
    let right_result = 0;
    crossbeam::scope(|scope| {
        
        let (left_array, right_array) = array.split_at(array.len()/2);
        
        let left_result = scope.spawn(move || {
                work_on(left_array)
            });

        right_result = work_on(right_array);
    });
    //how to access left_result here?
}

Thank in advance!


#2

Looks like scope takes a result returning closure:

pub fn scope<'a, F, R>(f: F) -> R 
    where F: FnOnce(&Scope<'a>) -> R

so you should be able to just

fn threaded_function() {    
    let (left_result, right_result) = crossbeam::scope(|scope| {
        
        let (left_array, right_array) = array.split_at(array.len()/2);
        
        let left_result = scope.spawn(move || {
                work_on(left_array)
            });

        right_result = work_on(right_array);
        (left_result, right_result)
    });
}

#3

Ah this looks nice. Thanks a lot!