在多线程程序中共享资源 C++ 与 Java
Sharing resources in Multi threaded programs C++ vs Java?
嗨,我正在研究在多个线程之间共享资源时C++和Java如何保护数据损坏的差异,在Java中,我们可以做很多事情,例如使用sync关键字:
public synchronized void inCounter
{
this.counter++;
}
在C++中,我们可以使用共享指针:
shared_ptr<Song> sp7(nullptr);
我的主要问题是我在使用C++和共享资源时必须考虑的主要区别,以及我们是否可以像 Java 一样使用同步,来自 Java 背景,我正在尝试了解有关C++的更多信息。
恕我直言,查看差异的价值有限。你真的需要忽略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
}
};
相关文章:
- 在java中解决这段代码时面临循环中的问题
- 尝试用java代码编译和运行c++代码
- 在这种情况下,java对象是否可以调用本机函数
- 在java中读取c++字节的位字段
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 使用已使用 java 编码的 openssl 解码数据
- SWIG Java 在使用 -DSWIGWORDSIZE64 时将int64_t转换为 jlong
- Android Java USB for native cpp
- 在由Sublime文本3编译后在cmd上显示Java程序输出
- C++ equivalent to Java Map getOrDefault?
- C++ 中的 Java 样式枚举
- 是否有技术原因阻止 Java 中的 final C++ 像 const 一样严格?
- 加密在 Windows、C++ 和 Java 中传输中的数据
- Java从C++回调到C++回调
- 在 c++ 中模拟输入并在 JAVA 中读取它?
- 用C++包装 Java 库 (JNI)
- 使用 TreeSet Java 对反转进行计数
- 验证openssl c++中的签名,这是由JAVA DSA签名的?
- 如何通过 JNI 将 C 字符串表情符号传递给 Java
- 如何从保存在 Java 中C++的字节数组中读取数字?