使用条件变量的C ++监视器类/包装器 [英] C++ monitor class/wrapper using condition variables

查看:64
本文介绍了使用条件变量的C ++监视器类/包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在C ++中创建包装类 W ,该包装类是使用指向通用对象 OBJ 的指针构造的.

I'm trying to create a wrapper class W in C++, which is constructed with a pointer to a generic object OBJ.

当您通过 W 调用 OBJ 方法之一时, W (包含条件变量 cv )发出 cv.wait()在调用 OBJ 方法之前,以及 cv.notify() OBJ 方法完成后

When you call one of OBJ methods through W, W (containing a condition variable cv) issues a cv.wait() before calling OBJ method and a cv.notify() when OBJ method has finished.

我已经能够通过特定类的继承来做到这一点,但是我想要一种类似于上述方法的通用方法.

I've been able to do it with inheritance for a specific class, but would like a generic approach like the one described above.

这是继承方法:

struct A
{
    virtual void foo(int i) { bar = i; };
    int bar;
};

struct B : public A
{
    void foo2(int i)
    {
        cv.wait(lck);
        this->foo(i);
        cv.notify_one();
    }
    std::condition_variable cv;
    std::unique_lock<std::mutex> lck;
};

我想要一些类似的东西:

I would like something in like:

template<class T>
struct C
{
    C(T *t) : t(t) {}

    T *operator->()
    {
        cv.wait(lck);
        return t;
        // notify_one when function has completed
    }

    T *t;
    std::condition_variable cv;
    std::unique_lock<std::mutex> lck;
};

我仅使用锁(但实际上不是监视器)找到了答案: https://stackoverflow.com/a/48408987

I found an answer using only locks (but that is not really a monitor): https://stackoverflow.com/a/48408987

推荐答案

下面是一个有效的示例:

Here is a working example:

#include <iostream>
#include <mutex>

template<class T>
class Wrapper {
    std::mutex m;
    T* p;

public:
    Wrapper(T& t) : p(&t) {}

    class Proxy {
        std::unique_lock<std::mutex> lock;
        T* p;

    public:
        Proxy(std::mutex& m, T* p)
            : lock(m)
            , p(p)
        {
            // Locked the mutex.
            std::cout << __PRETTY_FUNCTION__ << '\n';
        }

        Proxy(Proxy&& b) = default;

        ~Proxy() {
            std::cout << __PRETTY_FUNCTION__ << '\n';
            // Unlocked the mutex.
        }

        T* operator->() const { return p; }
    };

    Proxy operator->() { return Proxy(m, p); }
};

struct A {
    void f() { std::cout << __PRETTY_FUNCTION__ << '\n'; }
};

int main() {
    A a;
    Wrapper<A> w(a);
    w->f();
}

输出:

Wrapper<T>::Proxy::Proxy(std::mutex&, T*) [with T = A]
void A::f()
Wrapper<T>::Proxy::~Proxy() [with T = A]

有关完整的详细信息,请参见包装Bjarne Stroustrup的C ++成员函数调用.

See Wrapping C++ Member Function Calls by Bjarne Stroustrup for full details.

这篇关于使用条件变量的C ++监视器类/包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆