Arc on the stack

Hello,

I try to find a way to share a Mutex with multiple threads like Arc<Mutex> but without allocation the Mutex on the heap.
The solution provided in the Rust book is to allocate the Mutex on the heap with Arc<Mutex> but this is not satisfying. I know that the Mutex is still alive after thread ends and I don't want to do extra heap allocation jsut to satisfy the borrow checker.

This should not be a problem :

     let counter = Mutex::new(0);

    {
        let mut handles = vec![];
      
        for _ in 0..10{
            let handle = thread::spawn(||{
                let mut scoped = counter.lock().unwrap();
                *scoped += 1;
            });
            handles.push(handle);
        }
        
        for handle in handles {
            handle.join().unwrap();
        }
    } // All Threads are done here, even handles.

    println!("{}", counter.lock().unwrap()); // Doing this should be done without any problem

You're looking for the scoped threads API instead of std::thread one - the standard de-facto is AFAIK crossbeam.

11 Likes

This is an alternative yes, but I would have prefered to continue working with the std.
I will take a look at crossbeam.

Thank you

The standard library currently does not provide scoped threads, unfortunately.

I there any plan for this?

There's an RFC that you can read about here: 3151-scoped-threads - The Rust RFC Book

4 Likes

Thx a lot.
It will be a good exercise to create an Arc on the stack!

It doesn't really make sense to have reference-counting for something on the stack. You would need to use lifetimes to ensure that the clones don't outlive the stack memory it is stored in, but once you are using lifetimes, you don't also need the reference counting.

7 Likes

I see.
Thank you

FWIW, on nightly Rust, there is already a scoped API being featured (off that RFC):

#![feature(scoped_threads)]

fn main ()
{
    ::std::thread::scope(|s| {
        s.spawn(|| {});
    });
}

So this proves that even the standard library, on stable Rust, will eventually be able to handle this :slightly_smiling_face:

3 Likes

Greater! Thanks for sharing!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.