class Test
{
public:
Test() = default;
void CThreadFunc()
{
for (int i = 0; i < 10000; ++i)
{
//std::lock_guard lck(Test::m_s_ivalue_mutex); //m_iValue需要加锁才可正常工作
m_iValue++;
m_atomic_value++;//不加锁,也可正常工作
}
}
void Start()
{
std::vector 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 m_atomic_value = 0;//sta::atomic 原子操作
static std::mutex m_s_ivalue_mutex;
};