gpt4 book ai didi

c++ - 如何锁定使用带有初始化列表的构造函数的类的成员函数

转载 作者:行者123 更新时间:2023-11-28 05:24:54 27 4
gpt4 key购买 nike

这里有一段很棒的代码,说明了如何在对象的成员函数上使用锁。

 #include <thread>
#include <mutex>
#include <iostream>

class Foo
{
public:
void increment()
{
for ( int i = 0; i < 10000000; ++i )
{
std::lock_guard<std::mutex> lock(mtx); //lock mtx
++x;

// mtx is automatically released when lock
// goes out of scope -> RAII
}
}

void decrement()
{
for ( int i = 0; i < 10000000; ++i )
{
std::lock_guard<std::mutex> lock(mtx); //lock mtx
--x;

// mtx is automatically released when lock
// goes out of scope -> RAII
}
}

static int x;
static std::mutex mtx;
};

int Foo::x = 0;
std::mutex Foo::mtx;

int main()
{
std::thread t1(&Foo::increment, Foo());
std::thread t2(&Foo::decrement, Foo());

t1.join();
t2.join();

std::cout << Foo::x;
}

我的问题是,如果构造函数有一个数据成员初始化列表,如何实现它。可能吗?

最佳答案

如果 Foo 有数据成员初始化列表,则不需要额外的锁,因为每个线程都有它自己的 Foo 类实例。 Member initialization list指定直接和虚拟基类子对象和非静态数据成员的初始值设定项。

你只需要一个来控制线程间共享状态的一致性。就像示例中的静态 Foo::x 一样。

关于c++ - 如何锁定使用带有初始化列表的构造函数的类的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40751889/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com