Леонтий Хачуев Леонтий Хачуев - 1 year ago 121
C++ Question

Lock a resource (threads, C++)

I have two threads (first for read and second for write) and one shared resource (for example array). How to guard resource between threads? (block read, while second thread doing write) (Sorry for bad English)

Answer Source

std::mutex wrapped in std::lock_guard is the easiest way for novice in multithreading.

Something like this:

class Resource {
    T Read() { 
       std::lock_guard<std::mutex> lock(m_mutex);
       // read
    T Write() {
       std::lock_guard<std::mutex> lock(m_mutex);
       // write
    std::mutex m_mutex;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download