简体   繁体   English

线程安全访问成员变量

[英]Thread safe access to member variable

So I have a class which spawns a thread with the class object as parameter. 所以我有一个类,它以类对象作为参数生成一个线程。 Then in the thread I call a member function. 然后在线程中我调用一个成员函数。 I use Critical_Sections for synchronizing. 我使用Critical_Sections进行同步。

So would that implementation be thread safe? 那么实现是线程安全的吗? Because only the member is thread safe and not the class object. 因为只有成员是线程安全的而不是类对象。

    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());
    }

If the member is your critical section you should only lock the access to it. 如果该成员是您的关键部分,您应该只锁定对它的访问权限。

BTW, You can implement a Locker like: 顺便说一下,你可以实现一个像以下的储物柜:

class Locker
{
    mutex &m_;

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

And your code would look like: 你的代码看起来像:

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

Your implementation is thread safe because you have protected with mutex your access to attribute. 您的实现是线程安全的,因为您已使用互斥锁保护您对属性的访问权限。

Here, your class is a thread, so your object is a thread. 这里,你的类是一个线程,所以你的对象是一个线程。 It's what you do in your thread that tell if it is thread safe. 这是你在线程中所做的,它告诉它是否是线程安全的。

You get your value with a lock/unlock system and you write it with the same system. 您可以通过锁定/解锁系统获得价值,并使用相同的系统进行编写。 So your function is thread safe. 所以你的函数是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM