0

Hi I'm looking at the differences of how C++ and Java protect data corruption when sharing resources between multiple threads, in Java we can do many things like using the synchronized keyword:

public synchronized void inCounter
{
   this.counter++;
}

In C++ we can use a shared pointer:

shared_ptr<Song> sp7(nullptr);

My main question is the main differences I have to look at when using C++ and sharing resources and whether or not we can use synchronization the same as Java, coming from a Java background I am trying to learn more about C++.

Bhavesh
  • 882
  • 2
  • 9
  • 18

1 Answers1

0

Looking at the differences is of limited value imho. You really need to ignore what Java does and study up on how to do multithreading in C++.

It is a long time since I used Java but I seem to remember its synchronization is fairly intuitive and high level. In C++ you can use various techniques at different levels giving a great deal more flexibility and opportunity to be more efficient.

Here is a rough guide to how C++ can be used to implement higher level synchronization, similar to that of (what I remember of) Java. But remember there is much more to multithreading and shared resources than this.

#include <mutex>

class MyClass
{
    std::recursive_mutex class_mtx; // class level synchronization

    std::vector<std::string> vec;
    std::mutex vec_mtx; // specific resource synchronization

public:

    void /* synchronized */ func_1()
    {
        std::lock_guard<std::recursive_mutex> lock(class_mtx);

        // everything here is class level synchronized

        // only one thread at a time here or in func_2 or in other
        // blocks locked to class_mtx
    }

    void /* synchronized */ func_2()
    {
        std::lock_guard<std::recursive_mutex> lock(class_mtx);

        // everything here is class level synchronized

        // only one thread at a time here or in func_1 or in other
        // blocks locked to class_mtx
    }

    void func_3()
    {
        /* synchronized(this) */
        {
            std::lock_guard<std::recursive_mutex> lock(class_mtx);

            // everything here is class level synchronized
            // along with func_1 and func_2
        }

        // but not here
    }

    void func_4()
    {
        // do stuff

        /* sychronized(vec) */
        {
            std::lock_guard<std::mutex> lock(vec_mtx);

            // only the vector is protected

            // vector is locked until end of this block
        }

        // vector is not locked here
    }

    void func_5()
    {
        static std::mutex mtx; // single function synchronization

        std::lock_guard<std::mutex> lock(mtx);

        // this function is synchronized independent of other functions
    }
};
Galik
  • 47,303
  • 4
  • 80
  • 117