开发者

Looking for a function (or a macro) to return a boost::scoped_lock

I'm looking for code shortening idea. I'm using boost::scoped_lock to lock a boost::mutex but I want to shorten the amount of code I'm writing.

Currently I have a mutex def开发者_如何学JAVAined in my class and the member field called _sync. When I want to lock, I have to write:

scoped_lock<mutex> lock(_sync);

The tricky part is that this is a scoped lock, so I assume that if I write a static function to return the scoped_lock, then it will unlock as soon as it gets out of the function scope of the static function:

static scoped_lock<mutex> lock(mutex& sync)
{
    return scoped_lock<mutex>(sync);
}

This approach would make it really easy to type:

public void Object::modify()
{
    lock(_sync); // <-- nice and short! ;)

    // do something to modify the object
    //..
    // the mutex is unlocked when we leave the scope of modify
}

Is my assumption correct? Will the scoped_lock unlock immediately when it's returned by my static function?


Don't ...

when you type scoped_lock<mutex> lock(_sync) everybody reading your code knows what is going on, and you will also if you look at your code two years from know. Laziness is usually a bad motivation to create implementation. Unless you want to enforce usage, have more than just hundreds of places where you need to write this expression, just don't do it

In the time it took you to write up the question, and the amount of time that you spent pondering how to do it, and the amount of time all of us took to answer your question you probably could have written all the scoped_lock<mutex> lock(_sync) that you needed. Especially if you are using your IDEs completions support.


#define LOCK(a) scoped_lock<mutex> scopedLockVar(a)

public void Object::modify()
{
    LOCK(_sync); // <-- nice and short! ;)

    // do something to modify the object
    //..
    // the mutex is unlocked when we leave the scope of modify
}

You should use a safe name for the define... The compiler just uses find and replace for defines...


I would have thought that your lock will be compiled away altogether.

The point of the scoped lock is that it exists locally, so you must declare it locally. I don't think there is a way of getting round this in c++ without macros (which just hides the code somewhere else).

I reckon use a typedef, then everyone knows what you are doing.

typedef scoped_lock<mutex> lock; //at the start of your class
lock l(_sync); //in your function.

I don't think this is so bad....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜