简体   繁体   English

如何获取指向关联互斥量的指针

[英]How to acquire pointer to associated mutex

I'm working with mutex and when building the code, its throwing an error: 'error: use of deleted function 'std::mutex::mutex(const std::mutex&)'我正在使用互斥体,在构建代码时,它抛出一个错误: 'error: use of deleted function 'std::mutex::mutex(const std::mutex&)'

I understand why I'm getting this error, referred to this answer: Attempting to reference a deleted function when using a mutex .我明白为什么我会收到此错误,参考此答案: Attempting to reference a deleted function when using a mutex Now, I don't know how can I actually acquire the mutex stored in the instance being copied.现在,我不知道如何才能真正获取存储在被复制实例中的互斥体。 Any general example would help.任何一般的例子都会有所帮助。 Thanks!谢谢!

EDIT编辑

file.h文件.h

class A
{
    ...
    std::mutex taskMutex;
    bool isExecuting;
    ...
}

file.cpp文件.cpp

int function1
{
    std::unique_lock<std::mutex> lock(taskMutex);
    ...
    ( lambda func executing )
    isExecuting = true
    ...
    isExecuting = false
}

int function2
{
    while(isExecuting);
    std::unique_lock<std::mutex> lock(taskMutex);
}

Since each instance should be lockable, you need to lock the object while copying from it - which also may cause problems if it has non-default constructible member variables.由于每个实例都应该是可锁定的,因此您需要在从它复制时锁定 object - 如果它具有非默认的可构造成员变量,这也可能会导致问题。

One idea could be to add a unique_lock member that can lock the object being copied or moved from while doing the copying/moving.一个想法可能是添加一个unique_lock成员,该成员可以在进行复制/移动时锁定正在复制或移动的 object。

Here's an outline:这是一个大纲:

class Foo {
public:
    Foo() = default;

    Foo(const Foo& rhs) :  // copy constructor
        ul(rhs.mtx),       // lock the object being copied from
        member(rhs.member) // copy its members in the member initializer list
    {
        ul.unlock();       // unlock
    }

    Foo(Foo&& rhs) noexcept :         // move constructor
        ul(rhs.mtx),                  // lock the object being moved from
        member(std::move(rhs.member)) // move its members in the member init-list
    {
        ul.unlock();                  // unlock
    }

    Foo& operator=(const Foo& rhs) {         // copy assignment
        std::scoped_lock lock(mtx, rhs.mtx); // lock both objects involved
        member = rhs.member;                 // ... and copy
        return *this;
    }

    Foo& operator=(Foo&& rhs) noexcept {     // move assignment
        std::scoped_lock lock(mtx, rhs.mtx); // lock both objects involved
        member = std::move(rhs.member);      // ... and move
        return *this;
    }

private:
    std::unique_lock<std::mutex> ul; // used to lock rhs while copy/move constructing
    mutable std::mutex mtx;
    std::string member;
};

Note that the mutex and unique_lock member variables are not copied or moved at any time.请注意, mutexunique_lock成员变量在任何时候都不会被复制或移动。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM