jeudi 4 janvier 2018

are the following functions thread-safe?

#include <memory>
struct Apple
{
    ...
    void doSomething()
    {
    }
};

struct TestCase
{
    ...
    void run()   // multiple threads will call this function
    {
        thread_local std::unique_ptr<Apple> ptr(getBuffer());

        ptr->doSomething();
    }

    Apple* getBuffer() const
    {
        Apple* tmp = NULL;        
        tmp = new Apple(m_member);        
        return tmp;
    }

    int m_member;
};

Question 1> Is TestCase::getBuffer() thread-safe?

My understanding: YES(because all variables are local non-static)

Question 2> Is TestCase::run() thread-safe?

My understanding: YES(because ptr is flagged as thread_local) Note: I need to make the ptr thread_local because I only allow each thread to initialize ONCE!

Can someone please confirm my questions above? Thank you

Aucun commentaire:

Enregistrer un commentaire