C++ (Qt)#ifndef ATOMICDATA_H#define ATOMICDATA_H template <class T>class AtomicData{public: AtomicData() : m_flag(0) {} AtomicData(const T &data) : m_flag(0), m_data(data) {} AtomicData(const AtomicData<T> &other) : m_flag(0), m_data(other.get()) {} void set(const T &data) { while (m_flag) {} m_flag = 1; m_data = data; m_flag = 0; } T get() const { while (m_flag & 1) {} m_flag = 2; T data = m_data; m_flag = 0; return data; }private: mutable volatile char m_flag; T m_data; AtomicData<T> &operator=(const AtomicData<T> &);}; #endif // ATOMICDATA_H
C++ (Qt) while (m_flag) {} <- Здесь пробой m_flag = 1;
C++ (Qt)while (m_flag++); // <<-- Атомарна ли оно?critical_section();m_flag = 0;
C++ (Qt)while (m_flag++); // <<-- Атомарна ли оно?critical_section();m_flag = 0;
class Data {}class DataManager{public: ... SharedPointer<Data> data() const { ReadLocker lock; return m_data; } void setData(SharedPointer<Data> d) { WriteLocker lock; m_data = d; }private: SharedPointer<Data> m_data;}
class Data {}... SharedPointer<Data> data() const { ReadLocker lock; return m_data; } void setData(SharedPointer<Data> d) { WriteLocker lock; m_data = d; }
C++ (Qt)shared_ptr<Data> ptr;DataManager dataManager;...ptr = dataManager.data();