public synchronized void inCounter
{
this.counter++;
}在C++中,我们可以使用一个共享指针:
shared_ptr<Song> sp7(nullptr);我的主要问题是在使用C++和共享资源时必须查看的主要区别,以及我们是否可以使用与Java相同的同步,来自于Java背景我正在努力学习更多关于C++的知识。
发布于 2016-03-18 20:01:25
看一下这些差异的价值是有限的。你真的需要忽略Java是做什么的,研究一下如何在C++中做多线程。
我使用Java已经很久了,但我似乎记得它的同步是相当直观和高水平的。在C++中,您可以在不同的级别使用各种技术,从而获得更大的灵活性和更高效率的机会。
这是一个关于如何使用C++实现更高级别同步的粗略指南,类似于(我记得的) Java。但请记住,多线程和共享资源的意义远不止这些。
#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
}
};https://stackoverflow.com/questions/36081070
复制相似问题