21xrx.com
2024-09-19 09:29:36 Thursday
登录
文章检索 我的文章 写文章
如何实现C++多线程读写同一个对象?
2023-07-09 09:35:11 深夜i     --     --
C++ 多线程 读写 同一对象 实现

在C++编程中,多线程读写同一个对象是常见的需求。然而,正确地实现多线程读写同一个对象并确保线程安全并不容易。本文将介绍几种实现C++多线程读写同一个对象的方法。

1. 互斥锁

使用互斥锁是最基本的实现方法。互斥锁可以确保同一时刻只有一个线程可以访问对象。例如,如果一个线程正在写入对象,其他线程就不能同时读取或写入对象。在C++11中,可以使用std::mutex类实现互斥锁。示例代码如下:


#include <iostream>

#include <thread>

#include <mutex>

class MyClass {

public:

  void setValue(int value) {

    std::lock_guard<std::mutex> lock(m_mutex);

    m_value = value;

  }

  int getValue() const {

    std::lock_guard<std::mutex> lock(m_mutex);

    return m_value;

  }

private:

  int m_value;

  mutable std::mutex m_mutex;

};

int main() {

  MyClass obj;

  // write to object in one thread

  std::thread writer([&](){

    obj.setValue(42);

  });

  // read from object in another thread

  std::thread reader([&](){

    std::cout << "Value read from object: " << obj.getValue() << std::endl;

  });

  writer.join();

  reader.join();

  return 0;

}

2. 读写锁

使用读写锁可以提高程序的性能。在读取对象时,多个线程可以同时读取对象,而在写入对象时,只有一个线程可以写入对象,其他线程必须等待。在C++11中,可以使用std::shared_mutex类实现读写锁。示例代码如下:


#include <iostream>

#include <thread>

#include <shared_mutex>

class MyClass {

public:

  void setValue(int value) {

    std::lock_guard<std::shared_mutex> lock(m_mutex);

    m_value = value;

  }

  int getValue() const {

    std::shared_lock<std::shared_mutex> lock(m_mutex);

    return m_value;

  }

private:

  int m_value;

  mutable std::shared_mutex m_mutex;

};

int main() {

  MyClass obj;

  // write to object in one thread

  std::thread writer([&](){

    obj.setValue(42);

  });

  // read from object in another thread

  std::thread reader([&](){

    std::cout << "Value read from object: " << obj.getValue() << std::endl;

  });

  writer.join();

  reader.join();

  return 0;

}

3. 原子变量

原子变量是一种线程安全的类型,可以在多线程环境下原子地读取和写入变量。在C++11中,可以使用std::atomic类实现原子变量。示例代码如下:


#include <iostream>

#include <thread>

#include <atomic>

class MyClass {

public:

  void setValue(int value) {

    m_value.store(value, std::memory_order_relaxed);

  }

  int getValue() const {

    return m_value.load(std::memory_order_relaxed);

  }

private:

  std::atomic<int> m_value;

};

int main() {

  MyClass obj;

  // write to object in one thread

  std::thread writer([&](){

    obj.setValue(42);

  });

  // read from object in another thread

  std::thread reader([&](){

    std::cout << "Value read from object: " << obj.getValue() << std::endl;

  });

  writer.join();

  reader.join();

  return 0;

}

以上就是实现C++多线程读写同一个对象的几种方法。但是,需要注意的是,正确地实现多线程读写同一个对象并不容易,并且需要谨慎地处理内存模型和同步问题。因此,在实现多线程读写同一个对象时,建议使用现有的C++库,如boost或Qt等,或者使用已经被广泛测试的开源库,如Google的glog和gflags。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复