Click here to Skip to main content
13,831,444 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

22.6K views
52 bookmarked
Posted 11 May 2017
Licenced CPOL

tlock<>: Any C++ Object read/write Thread-safe Provider

, 14 Dec 2018
Rate this:
Please Sign up or sign in to vote.
An easy locking class for shared/exclusive mutex functions with upgrade/downgrade

GitHub project: https://github.com/WindowsNT/tlock

Introduction

Sometimes, you need an object to be accessible from many threads, either read only (so all threads can access), or write (so only one thread can access).This is called shared or exclusive access to an object.

The implementation is based on:

Now with upgrade and downgrade mechanism. The github repo includes rw.hpp (all you need) and an example GUI project that paints a box using multiple threads.

Using the Code

You need a proxy class so, when an object's method is called, the lock/unlock mechanism will be compiled automatically:

class proxy 
    {
    private:
        T *const p;
        RWMUTEX* m;
        HANDLE lm = 0;
        int me;
    public:
        proxy(T * const _p, RWMUTEX* _m, int _me) : p(_p), m(_m), 
              me(_me) { if (me == 2) m->LockWrite(); else lm = m->LockRead(); }
        ~proxy() { if (me == 2) m->ReleaseWrite(); else { m->ReleaseRead(lm); lm = 0;} }
        T* operator -> () { return p; }
        const T* operator -> () const { return p; }
        T* getp() { return p; }
        const T* getpc() const { return p; }
    };

The constructor and destructor of this class do all the work. They lock with RWMutex before the object method is to be called, and they unlock after the method has been called.

The tlock class will then look like this:

template <typename T> class tlock
{
private:
    mutable T t;
    mutable RWMUTEX m;

    class proxy
    {
        T *const p;
        RWMUTEX* m;
        HANDLE lm = 0;
        int me;
    public:
        proxy(T * const _p, RWMUTEX* _m, int _me) : p(_p), m(_m), me(_me) 
        { 
            if (me == 2) 
                m->LockWrite(); 
            else lm = m->LockRead(); 
        }
        ~proxy() 
        {
            if (me == 2) 
                m->ReleaseWrite(); 
            else 
            { 
                m->ReleaseRead(lm); 
                lm = 0; 
            } 
        }
        T* operator -> () { return p; }
        const T* operator -> () const { return p; }
        T* getp() { return p; }
        const T* getpc() const { return p; }
        void upgrade() 
        {
            if (me == 1)
            {
                lm = 0;
                m->Upgrade();
                me = 2;
            }
        }

        void downgrade()
        {
            if (me == 2)
            {
                lm = m->Downgrade();
                me = 1;
            }
        }

    };

public:
    template< typename ...Args>
    tlock(Args ... args) : t(args...) {}
    const proxy r() const
    {
        return proxy(&t, &m, 1);
    }
    proxy w()
    {
        return proxy(&t, &m, 2);
    }

    T& direct()
    {
        return t;
    }

    const T& direct() const
    {
        return t;
    }


    void readlock(std::function<void(const T&)> f) const
    {
        proxy mx(&t, &m, 1);
        f(*mx.getp());
    }
    void writelock(std::function<void(T&)> f)
    {
        proxy mx(&t, &m, 2);
        f(*mx.getp());
    }

    
   void rwlock(std::function<void(const T&,std::function<void(std::function<void(T&)>)>)> f)
    {
        proxy mx(&t, &m, 1);
        auto upfunc = [&](std::function<void(T&)> f2)
        {
            mx.upgrade();
            f2(*mx.getp());
            mx.downgrade();
        };
        f(*mx.getp(), upfunc);
    }
       

    proxy operator -> () { return w(); }
    const proxy operator -> () const { return r(); }

};

The r() method is called when you want read-only access to the object. This is the default when operator -> is called on a const object.

The w() method is called when you want write access to the object. This is the default for operator -> if the object is not constant.

The readlock() method is called when you want many operations in a locked read-only object, so it calls your function, passing a reference to the constant, locked object.

The writelock() method is called when you want many operations in a locked read-write object, so it calls your function, passing a reference to the locked object.

The rwlock() method is called when you want mainly read operations, but occassionally you want write upgrades.  It passes a reference to the locked object and an upgrade unction to upgrade the lock.

Let's see some incorrect usage (without tlock):

vector<int> s;
std::thread t1([&]() { s.push_back(0); });
std::thread t2([&]() { s.push_back(1); });
std::thread t3([&]() { s.push_back(2); });
std::thread t4([&]() { s.push_back(3); });
std::thread t5([&]() { s.push_back(4); });
t1.join();t2.join(); t3.join(); t4.join(); t5.join();

Boom!

And now, the correct usage:

tlock<vector<int>> s;
std::thread t1([&]() { s->push_back(0); });
std::thread t2([&]() { s->push_back(1); });
std::thread t3([&]() { s->push_back(2); });
std::thread t4([&]() { s->push_back(3); });
std::thread t5([&]() { s->push_back(4); });
t1.join();t2.join(); t3.join(); t4.join(); t5.join();

Now the writing is thread safe.

Using writelock() would be like that:

s.writelock([&](vector<int>& ss)
    {
    ss.push_back(100);
    ss.push_back(150); 
    ss.erase(ss.begin());
    // Safe operations, s is locked while in this function.
    })

And an example usage of rwlock():

s.rwlock([&](const vector<int>& vv, std::function<void(std::function<void(vector<int>&)>)> upgrfunc) 
{
	// vv read access
	upgrfunc([&](vector<int>& nn) 
	{
		// nn write access
		// function end downgrades
	});
});

History

  • 13-12-2018: Updated based on RWMUTEX for upgradable/downgradable locks, also direct access and upgrade function.
  • 12-12-2017: Updated based on RWMUTEX update
  • 30-08-2017: Added readlock and writelock convenience functions
  • 12-05-2017: First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Michael Chourdakis
Engineer
Greece Greece
I'm working in C++, PHP , Java, Windows, iOS and Android.

I 've a PhD in Digital Signal Processing and Artificial Intelligence and I specialize in Pro Audio and AI applications.

My home page: http://www.michaelchourdakis.com

You may also be interested in...

Comments and Discussions

 
Questionsome proposal Pin
Sergeant Kolja12-Dec-17 11:20
professionalSergeant Kolja12-Dec-17 11:20 
AnswerRe: some proposal Pin
Rick York12-Dec-17 14:06
mveRick York12-Dec-17 14:06 
AnswerRe: some proposal Pin
Michael Chourdakis14-Dec-17 2:39
mvaMichael Chourdakis14-Dec-17 2:39 
AnswerRe: some proposal Pin
Bob100014-Dec-18 5:42
professionalBob100014-Dec-18 5:42 
Questionquestion Pin
PanRuiSen26-Jul-17 16:21
memberPanRuiSen26-Jul-17 16:21 
AnswerRe: question Pin
Michael Chourdakis10-Aug-17 4:49
mvaMichael Chourdakis10-Aug-17 4:49 
QuestionDiff Pin
_kb_24-May-17 20:55
member_kb_24-May-17 20:55 
AnswerRe: Diff Pin
Michael Chourdakis26-May-17 11:54
mvaMichael Chourdakis26-May-17 11:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190114.1 | Last Updated 14 Dec 2018
Article Copyright 2017 by Michael Chourdakis
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid