2

I need to create unique_lock or shared lock based on a parameter in my function. I couldn't define properly in the scope of function. So I need to do something like this.

function (bool check) { lock; if (check) { lock = std::unique_lock<std::shared_mutex>(mutex); } else { lock = std::shared_lock<std::shared_mutex>(mutex); } lock.lock(); doTask.... 
4
  • 2
    You can make doTask.... a function and then call that function in each branch Commented May 1, 2018 at 21:55
  • So what I am trying to do is, if check is true only one thread can do the task otherwise every thread can do the task. This is why I want to create a shared lock. So every thread can access to a resource (a vector in my case) Commented May 1, 2018 at 21:57
  • All threads try to modify a vector, but the lock type is sent by the client so I need to create a lock based on the value of this boolean parameter Commented May 1, 2018 at 21:58
  • @NathanOliver I also couldn't see any other option. Thanks Commented May 1, 2018 at 22:05

3 Answers 3

3

Like this?

void function (bool check) { std::unique_lock<std::shared_mutex> u(mutex, std::defer_lock); std::shared_lock<std::shared_mutex> s(mutex, std::defer_lock); if (check) { u.lock(); } else { s.lock(); } doTask.... 
Sign up to request clarification or add additional context in comments.

2 Comments

u.lock is valid only within the if scope, it wont lock the entire function
@AhmetTanakol No. u.lock(); is a function call. It doesn't construct anything that goes out of scope.
1

Use std::variant:

void function (bool check) { std::variant<std::shared_lock<std::shared_mutex>, std::unique_lock<std::shared_mutex>> lock; if (check) { lock = std::unique_lock(mut); } else { lock = std::shared_lock(mut); } //doTask... } 

Comments

0

Since the caller is passing in the check condition anyway, you could give your function a template parameter to let the caller specify which type of lock to use, eg:

template<typename LockClass> function () { LockClass<std::shared_mutex> lock(mutex); doTask.... } 

//function (true); function<std::unique_lock>(); 

//function (false); function<std::shared_lock>(); 

Otherwise, you could split your code into multiple functions:

doTask() { ... } unique_function () { std::unique_lock<std::shared_mutex> lock(mutex); doTask(); } shared_function () { std::shared_lock<std::shared_mutex> lock(mutex); doTask(); } 

1 Comment

Unfortunately, I am not allowed the change function parameters or split the code into multiple functions

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.