Concurrency and Mutex lock with Thread spawns

spawn creates a new thread that executes concurrently with the main thread. When you try to get lock the mutex immediately after spawning, sometimes the other running thread is in the middle of holding the lock, others not.

The second bound in range syntax is exclusive, so 0..2 iteraters over 0 and 1 only.

No, the JoinHandle returned by spawn does not block on destruction, but you can block on it by calling .join().

I'm not sure where this quote is from.

You are using an Arc to share the Mutex value, which implements Sync, indicating that it can be shared between threads. There is no scoped thread in your example.

Yes, clone bumps the atomic ref count so that multiple pointers to the same Mutex can be shared between your threads. The ref count tracks the heap allocation that holds the Mutex, not the stack memory, though clone produces another copy of the Arc, which itself lives on the stack (containing a pointer to the Mutex on the heap).

Yes.

Yes.

1 Like