Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] About overhead of Mutex<T> in the perspective of memory size #821

Closed
invrtd-h opened this issue Sep 24, 2023 · 3 comments
Closed
Labels
question Further information is requested

Comments

@invrtd-h
Copy link

When I worked with C++ I found that C++ mutex is heavy:

static_assert(sizeof(std::mutex) == 64); // evaluates to be true, which means C++ mutex takes 64 bytes

So I avoided using, for example, this type:

struct Counter {
    mutable std::mutex m;
    int cnt;

    void inc() const {...}
}; // maybe 68 bytes, while basic int type uses only 4 bytes

std::vector<Counter> vec(1000000); // maybe requires 68MB? 

But I found that some Rust code uses Vec<Mutex<T>> type. Isn't it heavy? Or is Rust designed to avoid this problem?

@invrtd-h invrtd-h added the question Further information is requested label Sep 24, 2023
@tomtomjhj
Copy link
Member

tomtomjhj commented Sep 24, 2023

I think both the C++ standard and Rust reference don't specify how mutex should be implemented (and thus its size). So it's implementation-dependent.

On recent version of Rust on Linux, mutex is implemented with futex (https://github.com/rust-lang/rust/blob/master/library/std/src/sys/unix/locks/futex_mutex.rs, https://man7.org/linux/man-pages/man2/futex.2.html). So it only uses 4 bytes +4 bytes for alignment + an AtomicBool flag for poison. On older rust, mutex was implemented as pointer to pthread_mutex_t (which IIRC is about 40 bytes) because every type should be movable by default, while pthread_mutex_t isn't allowed to be moved.

@invrtd-h
Copy link
Author

Oh, I got it. Thank you for your explanation!

@Lee-Janggun
Copy link
Member

Lee-Janggun commented Sep 25, 2023

You may also be interested in rust-lang/rust#93740, which has more detail on how Rust moved from pthread to futex based locks for more efficient implementation.

As the issue also states, efficient lock implementation really depends on what the underlying OS provides, so something like mutex's size really can't be fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants