Мой код
Код: Выделить всё
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class NotesManager {
public:
optional getValue(size_t index) const {
shared_lock sharedLock(mutex_);
//unique_lock uniqueLock(mutex_);
if (index < notes_.size()) {
return notes_[index];
}
return std::nullopt;
}
void pushBack(const string& newNote) {
unique_lock uniqueLock(mutex_);
notes_.push_back(newNote);
}
private:
vector notes_;
mutable shared_mutex mutex_;
};
int main() {
NotesManager mgr;
vector threads;
for (int i = 0; i < 20000; ++i) {
if (i % 2 == 0) {
threads.emplace_back([i, &mgr]() {
const auto curr = std::to_string(i);
mgr.pushBack(curr);
});
} else {
threads.emplace_back([i, &mgr]() {
mgr.getValue(i);
});
threads.emplace_back([i, &mgr]() {
const auto curr = std::to_string(i);
mgr.pushBack(curr);
});
}
}
for (auto& t : threads) {
t.join();
}
}
./lock_example 0,12 с. пользовательская система 4.60s 138% процессор 3.412 всего
И второй тест - заменилиshared_lock на unique_lock -- ЕЩЕ БЫСТРЕЕ:
./lock_example 0,12 с пользователь 4,18 с система 126% ЦП 3,390 всего
Результаты почти такие же< /p>
Можно ли изменить мой пример, чтобы показать преимуществаshared_lock?
Подробнее здесь: https://stackoverflow.com/questions/784 ... ared-mutex
Мобильная версия