English 中文(简体)
Ensuring certain private functions can only be called from a locked state
原标题:

Say I have a class A:

class A {
public:
   A();

   void fetch_data() { return 1; }
   void write_x_data() {
     // lock this instance of A
     private_function1_which_assumes_locked();
     private_function2_which_assumes_locked();
     // unlock this instance of A
   }
   void write_y_data() {
     // lock this instance of A
     private_function1_which_assumes_locked();
     // unlock this instance of A
   }
private:
   void private_function1_which_assumes_locked();
   void private_function2_which_assumes_locked();
};

I want to guarantee that private_function*_which_assumed_locked() can never be called unless A is locked.

What s the best way to accomplish this? I ve got 5 or so public functions which need locking. These functions never call into each other, so I m not worried about deadlocking with these. Combined, these 5 public functions call into around 15 different private functions which need to assume the object is in a locked state. Obviously, I can t lock the private functions, since I d get deadlocks.

Feel free to provide answers in reasonably high-level abstractions, assuming the existences of Mutexes and Scopeguards.

In Python I might do something like this with decorators:

class locked_method(object):
    def __init__(self, f):
        self.f = f

    def __call__(self):
        # Do whatever is needed to lock
        self.f()
        # Do whatever is needed to unlock

class checklocked(object):
    def __init__(self, f):
        self.f = f

    def __call__(self):
        # check locked, if not, don t call self.f(),
        # and yell at me loudly for screwing up.
        self.f()

@locked_method
def func1():
    __function_which_assumes_locked()

@checklocked
def __function_which_assumes_locked():
    pass

NB: I ve not done much in the way of Python, so feel free to comment if my Python is wrong/stupid, but the point of this question is more the best way to accomplish this sort of thing in C++, so hopefully the Python provided is enough to give you an idea of what I want to do.

最佳回答

You could use a locker class, and require one to exist in order to call the private functions:

class A
{
public:
    void write()
    {
        Lock l(this);
        write(l);
    }

private:
    void lock();
    void unlock();
    void write(const Lock &);

    class Lock
    {
    public:
        explicit Lock(A *a) : parent(a) {parent->lock();}
        ~Lock() {parent->unlock();}
    private:
        A *parent;
    };
};
问题回答

This reminds me of a Dr. Dobb s article by Andrei Alexandrescu.

The idea is to use the fact that, in the same way that a const member function can t call a non-const one, a volatile member can t call a non-volatile one. He then uses volatile to "tag" the thread-safe functions, while non-volatile ones are "unsafe". So this fails to compile:

class Foo
{
public:
    // Not the "volatile"
    int External() volatile
    {
        return this->Internal();
    }

private:

    // Not volatile
    int Internal();
};

because this can t be converted from a Foo volatile* to a Foo*. A cast is necessary. This is made with a helper class that also plays the role as a RAII lock holder. So Foo becomes:

class Foo
{
public:
    int External() volatile
    {
        Lock self(this);
        return self->Internal();
    }

private:

    class Lock{
    public:
        explicit Lock(volatile Foo* Self)
            : m_Mutex.Aquire(),
              m_Self(const_cast<Foo*>(Self))
        {}

        ~Lock()
        {
            m_Mutex.Release();
        }

        Foo* operator->(){
            return m_Self;
        }

    private:
        SomeMutexType m_Mutex;
        Foo* m_Self;
    };


    int Internal();
};

You can use #Define to create a similar effect:

#define CheckIfLocked(func, criticalSection) 
    // here you can enter the critical section
    func 
    // exit critical section

You can use one of C++ locking mechanisms.

Use one of the "Try"-ing functions in as the first step in every private function - these functions just check if the lock is locked. If it isn t locked, throw an exception.

P.S. It could be interesting to make sure the private functions are only called from a locked state in compile-time... This would probably be possible in Haskell :)

Lock the object A once at the beginning of each public functions and release the lock when processing is done. The public functions are the entry points where processing begins anyway. You won t have to worry about locking in each private functions.

Have a look at RAII for locking/unlocking the object (or use something like boost::mutex::scoped_lock).

lock() function locks the mutex and puts thread id into a member variable. unlock() sets the member variable to 0 and unlocks the mutex

In your private functions check that thread id is that of your own thread, and complain loudly if not so.





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签