c++多线程编程,如何同时读取和修改对象的成员变量

怎么创建两个线程,一个通过p1使用get()读取值,一个使用p2通过set()修改值


#include
#include
#include
#include

using namespace std;

class A{
private:
    int x;

public:
    A(int _x):x(_x) {};

    int get()
    {
        return x;
    }

    void set(int y)
    {
        x = y;
        return;
    }
};



int main()
{
    shared_ptr p1 = make_shared(new A(1));
    shared_ptr p2(p1);
}

可以使用std::thread和std::mutex来创建两个线程,一个用于读取值,一个用于修改值。具体实现如下


#include <memory>
#include <thread>
#include <mutex>
#include <iostream>
 
using namespace std;
 
class A {
private:
    int x;
    mutex m;
 
public:
    A(int _x) : x(_x) {};
 
    int get() {
        lock_guard<mutex> lock(m);
        return x;
    }
 
    void set(int y) {
        lock_guard<mutex> lock(m);
        x = y;
    }
};
 
int main() {
    shared_ptr<A> p1 = make_shared<A>(1);
    shared_ptr<A> p2(p1);
 
    // 线程1:通过p1使用get()读取值
    thread t1([&](){
        while (true) {
            int x = p1->get();
            cout << "Thread 1 read value: " << x << endl;
        }
    });
 
    // 线程2:使用p2通过set()修改值
    thread t2([&](){
        int x = 0;
        while (true) {
            p2->set(x++);
            cout << "Thread 2 set value: " << x << endl;
        }
    });
 
    t1.join();
    t2.join();
 
    return 0;
}

在A类中使用了一个互斥锁std::mutex来保护共享资源x,防止多个线程同时访问和修改造成数据竞争问题。线程1通过p1调用get()方法读取值,线程2通过p2调用set()方法修改值。在main()函数中创建了两个线程t1和t2,分别运行读取和修改操作,通过调用join()等待线程结束。

c++多线程要用到“std::thread”,然后通过”std::promise“和”std::future“实现两个线程之间的值传递,代码如下:

#include <iostream>
#include <thread>
#include <future>
#include <chrono>

void setter(std::promise<int>& prom) {
    std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟耗时操作
    prom.set_value(42);
}

void getter(std::future<int>& fut) {
    std::cout << "Getter thread waiting for value...\n";
    auto value = fut.get();
    std::cout << "Getter thread got value: " << value << "\n";
}

int main() {
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();

    // 创建两个线程
    std::thread t1(setter, std::ref(prom));
    std::thread t2(getter, std::ref(fut));

    // 等待线程执行完成
    t1.join();
    t2.join();

    return 0;
}

注意事项:如果线程中发生了异常,”std::promise“和”std::future“会抛出异常,需要在代码中进行处理。此外,在使用std::future的get方法获取值时,如果std::promise中还没有设置值,线程会被阻塞,直到std::promise中有值可供获取。

希望可以帮到你~~~