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
}
};