How do I find elements with custom comparators with std::map in multithreaded code?

Finding elements with custom comparators in a `std::map` in multithreaded code can be challenging due to the complexities of concurrent access. This guide explores the techniques to achieve this safely and efficiently.
C++, std::map, custom comparators, multithreading, concurrency, thread safety

// Include necessary headers
#include <iostream>
#include <map>
#include <thread>
#include <mutex>

// Custom comparator structure
struct CustomComparator {
    bool operator()(const int& lhs, const int& rhs) const {
        return lhs < rhs; // Custom sorting logic
    }
};

std::map myMap; // Multithreaded access through a map
std::mutex mtx; // Mutex for synchronization

void insertIntoMap(int key, const std::string& value) {
    std::lock_guard<std::mutex> lock(mtx); // Lock mutex
    myMap[key] = value; // Insert element
}

void findInMap(int key) {
    std::lock_guard<std::mutex> lock(mtx); // Lock mutex
    auto it = myMap.find(key); // Find key
    if (it != myMap.end()) {
        std::cout << "Found: " << it->second << std::endl;
    } else {
        std::cout << "Key not found!" << std::endl;
    }
}

int main() {
    std::thread t1(insertIntoMap, 1, "Value1");
    std::thread t2(insertIntoMap, 2, "Value2");
    t1.join(); // Wait for thread to finish
    t2.join(); // Wait for thread to finish

    findInMap(1);
    findInMap(2);
    findInMap(3); // Key that does not exist

    return 0;
}
    

C++ std::map custom comparators multithreading concurrency thread safety