45

请,有人可以解释如何在 C++ 中使用和创建一个 unique_lock 吗?它既应该用于对监视器的任何过程进行互斥,也应该用于对条件变量执行 wait() ......我从文档中不明白我应该如何创建它。是否需要互斥锁?这是一个伪代码:

/* 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();
}
4

4 回答 4

65

std::unique_lock使用RAII模式。

当你想锁定一个互斥体时,你创建一个类型的局部变量,std::unique_lock将互斥体作为参数传递。当 unique_lock 被构造时,它将锁定互斥锁,并且它被破坏它将解锁互斥锁。更重要的是:如果抛出异常,std::unique_lock调用析构函数,因此互斥锁将被解锁。

例子:

#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
}        
于 2013-02-05T14:06:35.597 回答
10

使用条件变量的更详细的示例代码:

#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();
}
于 2016-09-14T08:15:49.083 回答
6

std::unique_lock<std::mutex>持有一个单独std::mutex对象的锁。您可以通过在构造函数中传递锁定对象与互斥锁相关联。除非您另外指定,否则互斥锁将立即被锁定。如果锁对象在销毁时持有锁,则析构函数将释放锁。通常,该std::unique_lock<std::mutex>对象将因此是一个局部变量,在您希望获取锁的位置声明。

在您的情况下,该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
}

请注意,我已将 替换为ifawhile以解决通话中的虚假唤醒问题wait()

于 2013-02-05T15:56:34.490 回答
-5

在这种情况下,我认为您需要做的就是:

m.lock();
// Critical section code
m.unlock();
于 2013-02-05T14:01:20.417 回答