【问题标题】:What feature corresponds to 'synchronized' in Java?什么特性对应于 Java 中的“同步”?
【发布时间】:2011-07-22 17:27:18
【问题描述】:

Java 中的synchronized 可以保证访问共享对象时的线程安全。 C++呢?

【问题讨论】:

  • C++ 没有提到线程。您需要依赖库支持。
  • @DavidHeffernan:从 C++11 开始,就是这样!
  • @Nawaz 是的,你看到这篇文章的日期了吗?
  • @DavidHeffernan:是的,我看到了 3 月 25 日 11 :P

标签: java c++ multithreading synchronization


【解决方案1】:

在 C++ 中使用以下代码:

#include <mutex>

std::mutex _mutex;

void f()
{
     std::unique_lock<std::mutex> lock(_mutex);
     // access your resource here.
}

【讨论】:

    【解决方案2】:

    尽管已经回答了这个问题,但根据this 文章的想法,我只使用标准库 (C++11) 对象制作了我的synchronized 关键字版本:

    #include <mutex>
    #define synchronized(m) \
        for(std::unique_lock<std::recursive_mutex> lk(m); lk; lk.unlock())
    

    你可以像这样测试它:

    #include <iostream>
    #include <iomanip>
    #include <mutex>
    #include <thread>
    #include <vector>
    
    #define synchronized(m) \
        for(std::unique_lock<std::recursive_mutex> lk(m); lk; lk.unlock())
    
    class Test {
        std::recursive_mutex m_mutex;
    public:
        void sayHello(int n) {
            synchronized(m_mutex) {
                std::cout << "Hello! My number is: ";
                std::cout << std::setw(2) << n << std::endl;
            }
        }    
    };
    
    int main() {
        Test test;
        std::vector<std::thread> threads;
        std::cout << "Test started..." << std::endl;
    
        for(int i = 0; i < 10; ++i)
            threads.push_back(std::thread([i, &test]() {
                for(int j = 0; j < 10; ++j) {
                    test.sayHello((i * 10) + j);
                    std::this_thread::sleep_for(std::chrono::milliseconds(100));
                }
            }));    
        for(auto& t : threads) t.join(); 
    
        std::cout << "Test finished!" << std::endl;
        return 0;
    }
    

    这只是 Java 的 synchonized 关键字的近似值,但它确实有效。没有它,前面示例的sayHello 方法可以实现为accepted answer 所说:

    void sayHello(unsigned int n) {
        std::unique_lock<std::recursive_mutex> lk(m_mutex);
    
        std::cout << "Hello! My number is: ";
        std::cout << std::setw(2) << n << std::endl;
    }
    

    【讨论】:

    • 如果作为模板实现会很棒,但我发现,除了一些众所周知的例外(例如 assert),使用 _#define_s 实现的代码是难以调试。
    【解决方案3】:

    C++03 中没有与 Java 中的 synchronized 等效的关键字。但是你可以使用 Mutex 来保证线程的安全。

    【讨论】:

      【解决方案4】:

      C++ 还没有内置的线程或同步,你必须为此使用库。 Boost.Thread 是一个很好的可移植库,旨在与 proposed threading facilities in C++0x 兼容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-29
        • 1970-01-01
        相关资源
        最近更新 更多