C++ 原子操作 std::atomic<T>
程序员文章站
2024-03-18 08:41:40
...
class Test
{
public:
Test() = default;
void CThreadFunc()
{
for (int i = 0; i < 10000; ++i)
{
//std::lock_guard<std::mutex> lck(Test::m_s_ivalue_mutex); //m_iValue需要加锁才可正常工作
m_iValue++;
m_atomic_value++;//不加锁,也可正常工作
}
}
void Start()
{
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i)
{
threads.push_back(std::thread(&Test::CThreadFunc, this));
}
for (auto& th : threads)
{
if (th.joinable())
{
th.join();
}
} std::cout << "m_iValue:" << m_iValue << ", m_atomic_value:" << m_atomic_value << std::endl;
}
private:
int m_iValue = 0;
std::atomic<int> m_atomic_value = 0;//sta::atomic<T> 原子操作
static std::mutex m_s_ivalue_mutex;
};
上一篇: 基于LinkedHashMap实现FIFO(先进先出)淘汰算法
下一篇: 四.基本数据结构-队列