简体   繁体   English

如何在c ++中使用/创建unique_lock?

[英]How to use/create unique_lock in c++?

Please, can anybody explain how to use and create an unique_lock in c++? 请问,任何人都可以解释如何在c ++中使用和创建unique_lock吗? It should be used both to get mutual exclusion to any procedure of the monitor and to be able to perform wait() on the condition variable...I'm not understanding from the documentation how I am supposed to create it. 它应该用于互斥监视器的任何过程,并能够对条件变量执行wait()...我不是从文档中了解我应该如何创建它。 Is necessary a mutex? 是必要的互斥? Here is a pseudo-code: 这是一个伪代码:

/* compile with g++, flags -std=c++0x -lpthread */

#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <string.h>
#include <unistd.h>

class monitorTh {

private:

    std::mutex m;
    std::condition_variable waitP;
    std::condition_variable waitC;
    char element[32];
    std::unique_lock::unique_lock l;

public:
    void produce(char* elemProd) {
        l.lock();
        if (/*already_present_element*/) {
            waitP.wait(l);
        }
        else {/*produce element*/}
        l.unlock();
    }

    void consume() {
        /*something specular*/
    }
};

int main(int argc, char* argv[]) {

    monitorTh* monitor = new monitorTh();
    char prodotto[32] = "oggetto";

    std::thread producer([&]() {
        monitor->produce(prodotto);
    });

    std::thread consumer([&]() {
        monitor->consume();
    });

    producer.join();
    consumer.join();
}

std::unique_lock use the RAII pattern. std::unique_lock使用RAII模式。

When you want to lock a mutex, you create a local variable of type std::unique_lock passing the mutex as parameter. 如果要锁定互斥锁,可以创建std::unique_lock类型的局部变量,并将互斥锁作为参数传递。 When the unique_lock is constructed it will lock the mutex, and it gets destructed it will unlock the mutex. 当构造unique_lock时,它将锁定互斥锁,并且它将被破坏,它将解锁互斥锁。 More importantly: If a exceptions is thrown, the std::unique_lock destructer will be called and so the mutex will be unlocked. 更重要的是:如果抛出异常, 调用std::unique_lock析构函数,因此将解锁互斥锁。

Example: 例:

#include<mutex>
int some_shared_var=0;

int func() {
    int a = 3;
    { //Critical section
        std::unique_lock<std::mutex> lock(my_mutex);
        some_shared_var += a;
    } //End of critical section
}        

std::unique_lock<std::mutex> holds a lock on a separate std::mutex object. std::unique_lock<std::mutex>持有一个单独的std::mutex对象的std::mutex You associate the lock object with the mutex by passing it in the constructor. 通过在构造函数中传递锁对象,可以将锁对象与互斥锁相关联。 Unless you specify otherwise, the mutex will be immediately locked. 除非您另行指定,否则将立即锁定互斥锁。 If the lock object holds the lock when it is destroyed then the destructor will release the lock. 如果锁定对象在销毁时保持锁定,那么析构函数将释放锁定。 Typically, the std::unique_lock<std::mutex> object will thus be a local variable, declared at the point where you wish to acquire the lock. 通常, std::unique_lock<std::mutex>对象因此将是一个局部变量,在您希望获取锁定的位置声明。

In your case, the produce() function could be written like this: 在您的情况下, produce()函数可以这样写:

void produce(char* elemProd) {
    std::unique_lock<std::mutex> lk(m); // lock the mutex
    while (/*already_present_element*/) { // condition variable waits may wake spuriously
        waitP.wait(lk);
    }
    {/*produce element*/}
    // lk releases the lock when it is destroyed
}

Note that I have replaced the if with a while to account for spurious wakes from the wait() call. 请注意,我已经用一段while替换了if来解决wait()调用中的虚假唤醒问题。

A more detailed sample code using condition variables: 使用条件变量的更详细的示例代码:

#include<mutex>
std::mutex(mu); //Global variable or place within class
std::condition_variable condition; //A signal that can be used to communicate between functions

auto MyFunction()->void
{
  std::unique_lock<mutex> lock(mu);
  //Do Stuff
  lock.unlock(); //Unlock the mutex
  condition.notify_one(); //Notify MyOtherFunction that this is done
}

auto MyOtherFunction()->void
{
   std::unique_lock<mutex> lock(mu);
   condition.wait(lock) //Wait for MyFunction to finish, a lambda can be passed also to protects against spurious wake up e.g (lock,[](){return *some condition*})
   lock.unlock();
}

In this case, I think all you need to do is: 在这种情况下,我认为你需要做的就是:

m.lock();
// Critical section code
m.unlock();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在调用其他使用unique_lock的函数的类中使用unique_lock? - How to use unique_lock in a class that calls other functions that use unique_lock? 声明RAII类型的C ++推荐方式(unique_lock) - C++ recommendet way of declaring RAII type (unique_lock) 请解释一下条件变量在c++线程中的使用,以及为什么我们需要同时使用`unique_lock`和`mutex` - Please explain the use of condition variables in c++ threads, and why do we need to use `unique_lock` and `mutex` alongwith this 何时使用C ++ 11互斥锁,锁,unique_lock,shared_lock等 - When to use C++11 mutex, lock, unique_lock, shared_lock, etc C ++ std :: lock和std :: unique_lock之间有什么区别? - C++ What are the differences between std::lock and std::unique_lock? C++中的unique_lock和shared_lock有什么区别 - What's the difference between unique_lock and shared_lock in C++ C ++线程:lock_guard可以拥有由unique_lock拥有的互斥体吗? - C++ thread: can lock_guard own a mutex that owned by a unique_lock? C ++在调用std :: unique_lock wait之前解锁std :: mutex - C++ Unlocking a std::mutex before calling std::unique_lock wait 根据条件创建 shared_lock 或 unique_lock - Create shared_lock or unique_lock based on a condition C ++ 11:为什么std :: condition_variable使用std :: unique_lock? - C++11: why does std::condition_variable use std::unique_lock?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM