user3668129
user3668129

Reputation: 4820

How to lock shared_mutex from one function and unlock it from other function?

I have a class which has several readers and several writers. I want to use read/write lock (using shared_mutex)

All the examples and information about this lock, use and release the lock in the same function: std::shared_mutex

I want to use (for reason I wan't explain here) shared_mutex in this way:

Lock4Read();
UnLock4Read();
Lock4Write();
UnLock4Write();

So I can lock the object I need, do my logic, and release it at the end (in other function).

How can I do it ?

I know I can do it using linux pthread_rwlock_rdlock, but can I do it using shared_mutex ?

Upvotes: 0

Views: 1025

Answers (1)

BartekPL
BartekPL

Reputation: 2420

I don't pretty sure that you want to do something like that, but check this, maybe it will be helpful for you :)

#include <iostream>
#include <mutex>
#include <shared_mutex>
#include <thread>

class ThreadMom {
 public:
  void Lock4Read() { mutex_.lock_shared(); }
  void UnLock4Read() { mutex_.unlock_shared(); }
  void Lock4Write() { mutex_.lock(); }
  void UnLock4Write() { mutex_.unlock(); }
 private:
  std::shared_mutex mutex_;
};

template <typename T> class Value {
 public:
  T get() const {return value_;}
  void set(const T& value) {value_ = value;}
 private:
  T value_;
};

int main() {
  ThreadMom mom;
  Value<int> value;
  value.set(0);
  auto increment_and_print = [&mom, &value](int which) {
    for (int i = 0; i < 3; i++) {
      mom.Lock4Write();
      value.set(i * which);
      mom.UnLock4Write();
      mom.Lock4Read();
      std::cout << std::this_thread::get_id() << ' ' << value.get() << '\n';
      mom.UnLock4Read();
    }
  };

  std::thread thread1(increment_and_print, 1);
  std::thread thread2(increment_and_print, 2);

  thread1.join();
  thread2.join();
}

Upvotes: 2

Related Questions