Search code examples
c++multithreadingthread-safetycritical-section

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.

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

Solution

  • 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.