문제

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());
    }
도움이 되었습니까?

해결책 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.

다른 팁

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top