c++ - 成员变量的线程安全访问

标签 c++ multithreading thread-safety critical-section

所以我有一个类生成一个以类对象作为参数的线程。然后在线程中我调用了一个成员函数。我使用 Critical_Sections 进行同步。

那么这个实现是线程安全的吗?因为只有成员是线程安全的而不是类对象。

    class TestThread : public CThread
    {
    public:
        virtual DWORD Work(void* pData) // Thread function
        {
            while (true)
            {
                if (Closing())
                {
                    printf("Closing thread");
                    return 0;
                }

                Lock();   //EnterCritical
                threadSafeVar++;
                UnLock(); //LeaveCritical

            }
        }

        int GetCounter()
        {
            int tmp;
            Lock();   //EnterCritical
            tmp = threadSafeVar;
            UnLock(); //LeaveCritical

            return tmp;
        }

    private:
        int threadSafeVar;
    };

.
.
.

    TestThread thr;

    thr.Run();

    while (true)
    {
        printf("%d\n",thr.GetCounter());
    }

最佳答案

如果成员是您的关键部分,您应该只锁定对它的访问。

顺便说一句,你可以像这样实现一个储物柜:

class Locker
{
    mutex &m_;

 public:
    Locker(mutex &m) : m_(m)
    {
      m.acquire();
    }
    ~Locker()
    {
      m_.release();
    }
};

你的代码看起来像:

mutex myVarMutex;
...
{
    Locker lock(myVarMutex);
    threadSafeVar++;
}
...
int GetCounter()
{
    Locker lock(myVarMutex);
    return threadSafeVar;
}

关于c++ - 成员变量的线程安全访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19710526/

相关文章:

java - 单次和双重检查延迟初始化

java - 使用 Swing 创建图像是线程安全的吗?

swift - 数组默认按值传递&线程安全

c++ - C++ 中的右值引用延长了临时对象的生命周期

multithreading - Racket refresh-now, thread, and yield

c++ - boost 互斥量和线程

java - 同样的计算怎么会产生不同的结果

Windows 下 Visual Studio 2012/英特尔编译器的 C++ double 失败

c++ - 为什么我更喜欢使用成员初始化列表?

c++ - 为什么来自 Bjarne 的 "Tour of C++"的代码有效?