C++ (Qt)QAtomicPointer <СData> theHead(0), theTail(0);QAtomicInt theCount(0); void PutData( CData * data ) // CData - Ваша структура { data->mNext = 0; while (true) { CData * head = theHead; if (head && !theHead.testAndSetAcquire(head, 0)) continue; // stop reading if (theCount++ == 0) { // list is empty theHead = theTail = data; return; } while (true) { CData * tail = theTail; if (!tail || !theTail.testAndSetAcquire(tail, data)) continue; // add data to list tail->mNext = data; break; } if (head) theHead = head; // enable reading break; }} CData * GetData( void ){ while (theCount) { CData * cur = theHead; if (!cur) continue; // wait for writer if (!theHead.testAndSetAcquire(cur, cur->mNext)) continue; --theCount; return cur; } return 0;}
class ShareData {public: ShareData() { myData = new char[1024]; } void lock() { mLock.lock(); } void unlock() { mLock.unlock(); } void setData(char* data) { lock(); // copy from data memcpy(data, myData, 1024); unlock(); } void getData(char* data) { lock(); // copy to data memcpy(myData, data, 1024); unlock(); }private: boost::mutex mLock; // можно использовать std::mutex, или QMutex char* myData;}
C++ (Qt)struct CAtomMutex { void Lock( void ) { while (!mVal.testAndSetAcquire(0, 1)) QThread::yieldCurrentThread(); } void Unlock( void ) { mVal = 0; } QAtomicInt mVal;};