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

时间:2016-03-18 09:47:10

标签: java c++ c++11 concurrency

您好我正在研究在多个线程之间共享资源时C ++和Java如何保护数据损坏的差异,在Java中我们可以做很多事情,比如使用synchronized关键字:

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

在C ++中,我们可以使用共享指针:

shared_ptr<Song> sp7(nullptr);

我的主要问题是在使用C ++和共享资源时我必须考虑的主要区别,以及我们是否可以使用与Java相同的同步,来自Java背景我正在尝试更多地了解C ++。

1 个答案:

答案 0 :(得分:0)

看看差异是有限的价值imho。你真的需要忽略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
    }
};
相关问题