首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++与Java在多线程程序中的资源共享?

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

Stack Overflow用户
提问于 2016-03-18 17:47:10
回答 1查看 323关注 0票数 0
代码语言:javascript
复制
public synchronized void inCounter
{
   this.counter++;
}

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

代码语言:javascript
复制
shared_ptr<Song> sp7(nullptr);

我的主要问题是在使用C++和共享资源时必须查看的主要区别,以及我们是否可以使用与Java相同的同步,来自于Java背景我正在努力学习更多关于C++的知识。

EN

回答 1

Stack Overflow用户

发布于 2016-03-18 20:01:25

看一下这些差异的价值是有限的。你真的需要忽略Java是做什么的,研究一下如何在C++中做多线程。

我使用Java已经很久了,但我似乎记得它的同步是相当直观和高水平的。在C++中,您可以在不同的级别使用各种技术,从而获得更大的灵活性和更高效率的机会。

这是一个关于如何使用C++实现更高级别同步的粗略指南,类似于(我记得的) Java。但请记住,多线程和共享资源的意义远不止这些。

代码语言:javascript
复制
#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
    }
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36081070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档