使用像锁一样的对象

时间:2017-03-29 14:16:12

标签: c++ multithreading

我有一个带有我自己的lock_guard,mutex等的库。(基本上mutex是nativ互斥体的包装器。现在我想更新几个具有锁定内部线程的对象。

让我们考虑一下这个类看起来是这样的:

class ICanBeUpdated
{
public:
    friend mango::lock_guard<ICanBeUpdated>;

    ICanBeUpdated()
    {
        //set some values, etc
    }

    void Update()
    {
        //do something, takes some time
    }

private:
    void lock() //required by the guard
    {
        m_Lock.lock();
    }

    void unlock() //required by the guard
    {
        m_Lock.unlock();
    }

    mango::mutex m_Lock; //regular mutex
};

我想做那样的事情:

int main()
{
    mango::archive::thread_pool pool(mango::getCPUCores(), true); //just a thread_pool

    lambda((ICanBeUpdated* actor)  //sorry my IDE has no c++11 support so I tricked my own lambda
    {
        mango::lock_guard<ICanBeUpdated> guard(*actor); //Locks the object like it were a mutex to block other stakeholders from changing it while it's updating
        actor->Update(); 
        return 0; 
    }, 1); //exp1

    mango::shared_ptr<mango::vector<ICanBeUpdated*> > Actors = getActors(); //creates a vector of actors

    for (int i = 0; Actors->size() > i; ++i)
    {
        pool.run(exp1, Actors->at(i));
    }

    return 0;
}

是否可以像这样使用带锁的非锁定对象?

mango::lock_guard<ICanBeUpdated> guard(*actor);

如果不是,为什么我总是必须将互斥锁传递给守卫来锁定它,还是应该实现另一种锁定角色的方式?

0 个答案:

没有答案