Synchronizaton. What are the best options to provide synchronization for member class functions in C++ 14 or C++ 11

Hi ppl :),

I am looking for deadlock free and easy synchronization constructs to provide synchronization for class member functions.
Please consider the following example. Thanks :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Integer
{
    private:
        int x;
    public:
        Integer () : x(0) {}
        ~Integer() {}
        
        void increment()
        {   
            /*what is the best way that c++ 14 or c++ 11 provides to enable synchronization here
             * something like : "enter_synchronized();", a simple and deadlock free construct.*/
            ++x;
            //end_synchronized()
        }   
};      

Integer i;

void incrementInteger()     //This function can be called by multiple threads.
{   
    i.increment()
} 
For a TriviallyCopyable type, wrap in std::atomic
http://en.cppreference.com/w/cpp/atomic

1
2
3
4
5
6
7
8
#include <atomic>

class Integer
{
    private: std::atomic<int> x{0} ;

    public: int increment() { return ++x ; } // note: ++x yields a prvalue
};


Otherwise, guard with an appropriate mutex (the simplest would be std::mutex or std::recursive_mutex)
http://en.cppreference.com/w/cpp/header/mutex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <mutex>
#include <string>

class String
{
    private:
        std::string text ;
        std::mutex text_guard ;

    public:
        std::string append( std::string str )
        {
            std::lock_guard<std::mutex> lock(text_guard) ;
            return text += str ;
        }
};
Thanks @JLBorges :)
Topic archived. No new replies allowed.