Junior — Senior
Analysis of the correctness and efficiency of mutex usage
livecode
Task condition
Conduct a review of the provided code: identify potential issues, suggest improvements, and evaluate the correctness of mutex usage. Explain how the operator< works in a multithreaded environment.
# include <iostream>
# include <thread>
# include <mutex>
struct Data {
explicit Data(size_t value)
: m_value(value) {}
friend bool operator<(Data& lhs, Data& rhs);
private:
size_t m_value = 0u;
size_t m_compare_counter = 0u;
mutable std::mutex m_mutex;
};
bool operator<(Data& lhs, Data& rhs) {
std::lock_guard<std::mutex> lhs_lock(lhs.m_mutex);
std::lock_guard<std::mutex> rhs_lock(rhs.m_mutex);
++lhs.m_compare_counter;
++rhs.m_compare_counter;
return lhs.m_value < rhs.m_value;
}
Data data_1(10u);
Data data_2(20u);
void compare_1() {
for (size_t i = 0u; i < 100u; ++i) {
const bool result = data_1 < data_2;
}
}
void compare_2() {
for (size_t i = 0u; i < 100u; ++i) {
const bool result = data_2 < data_1;
}
}
int main(int argc, char** argv) {
std::thread thread_1(compare_1);
std::thread thread_2(compare_2);
if (thread_1.joinable()) {
thread_1.join();
}
if (thread_2.joinable()) {
thread_2.join();
}
return EXIT_SUCCESS;
}