mercredi 5 août 2015

What's the best practise for store object pointer in a thread safe way?

Suppose we are designing a note manager. The GUI Thread A and background sync Thread B could hold the same note pointer at the same time.

Thus I designed following classes.

class NoteManager {
    std::mutex lock.
    public:
        Note* getNote(const std::wstring& noteId) {
            lock_guard lock
            if (exists)
                find the note for noteId.
                note->addRef();
                return note;
            else
                return nullptr;
        }

        void  addNote(Note*) {
            lock_guard lock

        }

        void deleteNote(const std::wstring& noteid) {
            lock_guard lock
            find the note for noteid.
            if (exists)
                noteList_.erase(note);
                note->setInvalid(true);
                note->unref();

        }

    private:
        std::list<Note*> noteList_;
};

class Note : public RefCountedPtr<Note> {
    public:
        void setInvalid(bool valid);
        void setTitle(const std::wstring&);
        std::wstring getTitle() const;
        void otherActions() {
            if (invalid)
                return;
            otherwise 
                do the action.
        }
    private:
        std::atomic<bool> valid_;
};

GuiA:
    Note* note = NoteMan::getNote(L"01432147");
    if (note) {
        do something.
        //here the syncb deleted.
        note->otherActions()
        // would direct returned without waste time on 
        // something that is deleted.
    }

SyncB:
    NoteMan::deleteNote(L"01432147");

Is this thread safe suppose the note class itself is thread-safe? Or is therer any design pattern/best practise for such scenario?

Aucun commentaire:

Enregistrer un commentaire