Что такое Mutex<T>
2025-03-02 19:37Продолжаем изучать примитивы языка Rust. В этом деле Грок неплохой помощник. Как выясняется, тип Mutex<T> представляет собой удобную комбинацию классов std::mutex и std::unique_lock из Си++.
Question: Please show me a possible implementation of type Mutex<T> in C++.
I'll provide an implementation of a Mutex<T> type in C++ that mimics Rust's Mutex. Rust's Mutex provides mutual exclusion with a lock guard pattern, so we'll create a similar construct in C++ using the standard library's threading primitives.
Here's a possible implementation: mutex.cpp.
Question: Please show me a possible implementation of type Mutex<T> in C++.
I'll provide an implementation of a Mutex<T> type in C++ that mimics Rust's Mutex. Rust's Mutex provides mutual exclusion with a lock guard pattern, so we'll create a similar construct in C++ using the standard library's threading primitives.
Here's a possible implementation: mutex.cpp.
#include <mutex>
#include <memory>
template<typename T>
class Mutex {
private:
T data;
std::mutex mtx;
public:
// Constructor
explicit Mutex(T value) : data(std::move(value)) {}
// Lock guard class (similar to Rust's MutexGuard)
class LockGuard {
private:
T& data_ref;
std::unique_lock<std::mutex> lock;
public:
LockGuard(T& d, std::mutex& m)
: data_ref(d), lock(m) {}
// Access the underlying data
T& operator*() { return data_ref; }
T* operator->() { return &data_ref; }
};
// Lock method that returns the guard
LockGuard lock() {
return LockGuard(data, mtx);
}
// Prevent copying
Mutex(const Mutex&) = delete;
Mutex& operator=(const Mutex&) = delete;
// Allow move construction
Mutex(Mutex&&) = default;
Mutex& operator=(Mutex&&) = default;
};