Question

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());
    }
Was it helpful?

Solution 2

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.

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top