在多线程程序中共享资源 C++ 与 Java

Sharing resources in Multi threaded programs C++ vs Java?

本文关键字:C++ Java 共享资源 多线程 程序      更新时间:2023-10-16

嗨,我正在研究在多个线程之间共享资源时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
    }
};