diff --git a/libs/image/3rdparty/lock_free_map/concurrent_map.h b/libs/image/3rdparty/lock_free_map/concurrent_map.h index 30b1e282c5..6666be0b05 100644 --- a/libs/image/3rdparty/lock_free_map/concurrent_map.h +++ b/libs/image/3rdparty/lock_free_map/concurrent_map.h @@ -1,369 +1,375 @@ /*------------------------------------------------------------------------ Junction: Concurrent data structures in C++ Copyright (c) 2016 Jeff Preshing Distributed under the Simplified BSD License. Original location: https://github.com/preshing/junction This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE file for more information. ------------------------------------------------------------------------*/ #ifndef CONCURRENTMAP_H #define CONCURRENTMAP_H #include "leapfrog.h" template , class VT = DefaultValueTraits > class ConcurrentMap { public: typedef K Key; typedef V Value; typedef KT KeyTraits; typedef VT ValueTraits; typedef quint32 Hash; typedef Leapfrog Details; private: Atomic m_root; - QSBR m_gc; +// QSBR m_gc; + GarbageCollector m_gc; public: ConcurrentMap(quint64 capacity = Details::InitialSize) : m_root(Details::Table::create(capacity)) { } ~ConcurrentMap() { typename Details::Table* table = m_root.loadNonatomic(); table->destroy(); } - QSBR &getGC() +// QSBR &getGC() +// { +// return m_gc; +// } + + GarbageCollector &getGC() { return m_gc; } // publishTableMigration() is called by exactly one thread from Details::TableMigration::run() // after all the threads participating in the migration have completed their work. void publishTableMigration(typename Details::TableMigration* migration) { // There are no racing calls to this function. typename Details::Table* oldRoot = m_root.loadNonatomic(); m_root.store(migration->m_destination, Release); Q_ASSERT(oldRoot == migration->getSources()[0].table); // Caller will GC the TableMigration and the source table. } // A Mutator represents a known cell in the hash table. // It's meant for manipulations within a temporary function scope. // Obviously you must not call QSBR::Update while holding a Mutator. // Any operation that modifies the table (exchangeValue, eraseValue) // may be forced to follow a redirected cell, which changes the Mutator itself. // Note that even if the Mutator was constructed from an existing cell, // exchangeValue() can still trigger a resize if the existing cell was previously marked deleted, // or if another thread deletes the key between the two steps. class Mutator { private: friend class ConcurrentMap; ConcurrentMap& m_map; typename Details::Table* m_table; typename Details::Cell* m_cell; Value m_value; // Constructor: Find existing cell Mutator(ConcurrentMap& map, Key key, bool) : m_map(map), m_value(Value(ValueTraits::NullValue)) { Hash hash = KeyTraits::hash(key); for (;;) { m_table = m_map.m_root.load(Consume); m_cell = Details::find(hash, m_table); if (!m_cell) { return; } Value value = m_cell->value.load(Consume); if (value != Value(ValueTraits::Redirect)) { // Found an existing value m_value = value; return; } // We've encountered a Redirect value. Help finish the migration. m_table->jobCoordinator.participate(); // Try again using the latest root. } } // Constructor: Insert or find cell Mutator(ConcurrentMap& map, Key key) : m_map(map), m_value(Value(ValueTraits::NullValue)) { Hash hash = KeyTraits::hash(key); for (;;) { m_table = m_map.m_root.load(Consume); quint64 overflowIdx; switch (Details::insertOrFind(hash, m_table, m_cell, overflowIdx)) { // Modifies m_cell case Details::InsertResult_InsertedNew: { // We've inserted a new cell. Don't load m_cell->value. return; } case Details::InsertResult_AlreadyFound: { // The hash was already found in the table. Value value = m_cell->value.load(Consume); if (value == Value(ValueTraits::Redirect)) { // We've encountered a Redirect value. break; // Help finish the migration. } // Found an existing value m_value = value; return; } case Details::InsertResult_Overflow: { // Unlike ConcurrentMap_Linear, we don't need to keep track of & pass a "mustDouble" flag. // Passing overflowIdx is sufficient to prevent an infinite loop here. // It defines the start of the range of cells to check while estimating total cells in use. // After the first migration, deleted keys are purged, so if we hit this line during the // second loop iteration, every cell in the range will be in use, thus the estimate will be 100%. // (Concurrent deletes could result in further iterations, but it will eventually settle.) Details::beginTableMigration(m_map, m_table, overflowIdx); break; } } // A migration has been started (either by us, or another thread). Participate until it's complete. m_table->jobCoordinator.participate(); // Try again using the latest root. } } public: Value getValue() const { // Return previously loaded value. Don't load it again. return Value(m_value); } Value exchangeValue(Value desired) { Q_ASSERT(desired != Value(ValueTraits::NullValue)); Q_ASSERT(desired != Value(ValueTraits::Redirect)); Q_ASSERT(m_cell); // Cell must have been found or inserted for (;;) { Value oldValue = m_value; if (m_cell->value.compareExchangeStrong(m_value, desired, ConsumeRelease)) { // Exchange was successful. Return previous value. Value result = m_value; m_value = desired; // Leave the mutator in a valid state return result; } // The CAS failed and m_value has been updated with the latest value. if (m_value != Value(ValueTraits::Redirect)) { if (oldValue == Value(ValueTraits::NullValue) && m_value != Value(ValueTraits::NullValue)) { // racing write inserted new value } // There was a racing write (or erase) to this cell. // Pretend we exchanged with ourselves, and just let the racing write win. return desired; } // We've encountered a Redirect value. Help finish the migration. Hash hash = m_cell->hash.load(Relaxed); for (;;) { // Help complete the migration. m_table->jobCoordinator.participate(); // Try again in the new table. m_table = m_map.m_root.load(Consume); m_value = Value(ValueTraits::NullValue); quint64 overflowIdx; switch (Details::insertOrFind(hash, m_table, m_cell, overflowIdx)) { // Modifies m_cell case Details::InsertResult_AlreadyFound: m_value = m_cell->value.load(Consume); if (m_value == Value(ValueTraits::Redirect)) { break; } goto breakOuter; case Details::InsertResult_InsertedNew: goto breakOuter; case Details::InsertResult_Overflow: Details::beginTableMigration(m_map, m_table, overflowIdx); break; } // We were redirected... again } breakOuter:; // Try again in the new table. } } void assignValue(Value desired) { exchangeValue(desired); } Value eraseValue() { Q_ASSERT(m_cell); // Cell must have been found or inserted for (;;) { if (m_value == Value(ValueTraits::NullValue)) { return Value(m_value); } if (m_cell->value.compareExchangeStrong(m_value, Value(ValueTraits::NullValue), Consume)) { // Exchange was successful and a non-NULL value was erased and returned by reference in m_value. Q_ASSERT(m_value != Value(ValueTraits::NullValue)); // Implied by the test at the start of the loop. Value result = m_value; m_value = Value(ValueTraits::NullValue); // Leave the mutator in a valid state return result; } // The CAS failed and m_value has been updated with the latest value. if (m_value != Value(ValueTraits::Redirect)) { // There was a racing write (or erase) to this cell. // Pretend we erased nothing, and just let the racing write win. return Value(ValueTraits::NullValue); } // We've been redirected to a new table. Hash hash = m_cell->hash.load(Relaxed); // Re-fetch hash for (;;) { // Help complete the migration. m_table->jobCoordinator.participate(); // Try again in the new table. m_table = m_map.m_root.load(Consume); m_cell = Details::find(hash, m_table); if (!m_cell) { m_value = Value(ValueTraits::NullValue); return m_value; } m_value = m_cell->value.load(Relaxed); if (m_value != Value(ValueTraits::Redirect)) { break; } } } } }; Mutator insertOrFind(Key key) { return Mutator(*this, key); } Mutator find(Key key) { return Mutator(*this, key, false); } // Lookup without creating a temporary Mutator. Value get(Key key) { Hash hash = KeyTraits::hash(key); for (;;) { typename Details::Table* table = m_root.load(Consume); typename Details::Cell* cell = Details::find(hash, table); if (!cell) { return Value(ValueTraits::NullValue); } Value value = cell->value.load(Consume); if (value != Value(ValueTraits::Redirect)) { return value; // Found an existing value } // We've been redirected to a new table. Help with the migration. table->jobCoordinator.participate(); // Try again in the new table. } } Value assign(Key key, Value desired) { Mutator iter(*this, key); return iter.exchangeValue(desired); } Value exchange(Key key, Value desired) { Mutator iter(*this, key); return iter.exchangeValue(desired); } Value erase(Key key) { Mutator iter(*this, key, false); return iter.eraseValue(); } // The easiest way to implement an Iterator is to prevent all Redirects. // The currrent Iterator does that by forbidding concurrent inserts. // To make it work with concurrent inserts, we'd need a way to block TableMigrations. class Iterator { private: typename Details::Table* m_table; quint64 m_idx; Key m_hash; Value m_value; public: Iterator() = default; Iterator(ConcurrentMap& map) { // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead: m_table = map.m_root.load(Consume); m_idx = -1; next(); } void setMap(ConcurrentMap& map) { m_table = map.m_root.load(Consume); m_idx = -1; next(); } void next() { Q_ASSERT(m_table); Q_ASSERT(isValid() || m_idx == -1); // Either the Iterator is already valid, or we've just started iterating. while (++m_idx <= m_table->sizeMask) { // Index still inside range of table. typename Details::CellGroup* group = m_table->getCellGroups() + (m_idx >> 2); typename Details::Cell* cell = group->cells + (m_idx & 3); m_hash = cell->hash.load(Relaxed); if (m_hash != KeyTraits::NullHash) { // Cell has been reserved. m_value = cell->value.load(Relaxed); Q_ASSERT(m_value != Value(ValueTraits::Redirect)); if (m_value != Value(ValueTraits::NullValue)) return; // Yield this cell. } } // That's the end of the map. m_hash = KeyTraits::NullHash; m_value = Value(ValueTraits::NullValue); } bool isValid() const { return m_value != Value(ValueTraits::NullValue); } Key getKey() const { Q_ASSERT(isValid()); // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead: return KeyTraits::dehash(m_hash); } Value getValue() const { Q_ASSERT(isValid()); return m_value; } }; }; #endif // CONCURRENTMAP_LEAPFROG_H diff --git a/libs/image/3rdparty/lock_free_map/leapfrog.h b/libs/image/3rdparty/lock_free_map/leapfrog.h index 03afe2d2f3..65ee6fe509 100644 --- a/libs/image/3rdparty/lock_free_map/leapfrog.h +++ b/libs/image/3rdparty/lock_free_map/leapfrog.h @@ -1,547 +1,553 @@ /*------------------------------------------------------------------------ Junction: Concurrent data structures in C++ Copyright (c) 2016 Jeff Preshing Distributed under the Simplified BSD License. Original location: https://github.com/preshing/junction This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE file for more information. ------------------------------------------------------------------------*/ #ifndef LEAPFROG_H #define LEAPFROG_H #include "map_traits.h" #include "simple_job_coordinator.h" #include "qsbr.h" template struct Leapfrog { typedef typename Map::Hash Hash; typedef typename Map::Value Value; typedef typename Map::KeyTraits KeyTraits; typedef typename Map::ValueTraits ValueTraits; static const quint64 InitialSize = 8; static const quint64 TableMigrationUnitSize = 32; static const quint64 LinearSearchLimit = 128; static const quint64 CellsInUseSample = LinearSearchLimit; Q_STATIC_ASSERT(LinearSearchLimit > 0 && LinearSearchLimit < 256); // Must fit in CellGroup::links Q_STATIC_ASSERT(CellsInUseSample > 0 && CellsInUseSample <= LinearSearchLimit); // Limit sample to failed search chain struct Cell { Atomic hash; Atomic value; }; struct CellGroup { // Every cell in the table actually represents a bucket of cells, all linked together in a probe chain. // Each cell in the probe chain is located within the table itself. // "deltas" determines the index of the next cell in the probe chain. // The first cell in the chain is the one that was hashed. It may or may not actually belong in the bucket. // The "second" cell in the chain is given by deltas 0 - 3. It's guaranteed to belong in the bucket. // All subsequent cells in the chain is given by deltas 4 - 7. Also guaranteed to belong in the bucket. Atomic deltas[8]; Cell cells[4]; }; struct Table { const quint64 sizeMask; // a power of two minus one QMutex mutex; // to DCLI the TableMigration (stored in the jobCoordinator) SimpleJobCoordinator jobCoordinator; // makes all blocked threads participate in the migration Table(quint64 sizeMask) : sizeMask(sizeMask) { } static Table* create(quint64 tableSize) { Q_ASSERT(isPowerOf2(tableSize)); Q_ASSERT(tableSize >= 4); quint64 numGroups = tableSize >> 2; Table* table = (Table*) std::malloc(sizeof(Table) + sizeof(CellGroup) * numGroups); new (table) Table(tableSize - 1); for (quint64 i = 0; i < numGroups; i++) { CellGroup* group = table->getCellGroups() + i; for (quint64 j = 0; j < 4; j++) { group->deltas[j].storeNonatomic(0); group->deltas[j + 4].storeNonatomic(0); group->cells[j].hash.storeNonatomic(KeyTraits::NullHash); group->cells[j].value.storeNonatomic(Value(ValueTraits::NullValue)); } } return table; } void destroy() { this->Table::~Table(); std::free(this); } CellGroup* getCellGroups() const { return (CellGroup*)(this + 1); } quint64 getNumMigrationUnits() const { return sizeMask / TableMigrationUnitSize + 1; } }; - class TableMigration : public SimpleJobCoordinator::Job + class TableMigration : public SimpleJobCoordinator::Job, public Property { public: struct Source { Table* table; Atomic sourceIndex; }; Map& m_map; Table* m_destination; Atomic m_workerStatus; // number of workers + end flag Atomic m_overflowed; Atomic m_unitsRemaining; quint64 m_numSources; TableMigration(Map& map) : m_map(map) { } static TableMigration* create(Map& map, quint64 numSources) { TableMigration* migration = (TableMigration*) std::malloc(sizeof(TableMigration) + sizeof(TableMigration::Source) * numSources); new (migration) TableMigration(map); migration->m_workerStatus.storeNonatomic(0); migration->m_overflowed.storeNonatomic(false); migration->m_unitsRemaining.storeNonatomic(0); migration->m_numSources = numSources; // Caller is responsible for filling in sources & destination return migration; } virtual ~TableMigration() override - { - } - - void destroy() { // Destroy all source tables. - for (quint64 i = 0; i < m_numSources; i++) - if (getSources()[i].table) + for (quint64 i = 0; i < m_numSources; i++) { + if (getSources()[i].table) { getSources()[i].table->destroy(); - // Delete the migration object itself. - this->TableMigration::~TableMigration(); - std::free(this); + } + } } +// void destroy() +// { +// // Destroy all source tables. +// for (quint64 i = 0; i < m_numSources; i++) +// if (getSources()[i].table) +// getSources()[i].table->destroy(); +// // Delete the migration object itself. +// this->TableMigration::~TableMigration(); +// std::free(this); +// } + Source* getSources() const { return (Source*)(this + 1); } bool migrateRange(Table* srcTable, quint64 startIdx); virtual void run() override; }; static Cell* find(Hash hash, Table* table) { Q_ASSERT(table); Q_ASSERT(hash != KeyTraits::NullHash); quint64 sizeMask = table->sizeMask; // Optimistically check hashed cell even though it might belong to another bucket quint64 idx = hash & sizeMask; CellGroup* group = table->getCellGroups() + (idx >> 2); Cell* cell = group->cells + (idx & 3); Hash probeHash = cell->hash.load(Relaxed); if (probeHash == hash) { return cell; } else if (probeHash == KeyTraits::NullHash) { return cell = NULL; } // Follow probe chain for our bucket quint8 delta = group->deltas[idx & 3].load(Relaxed); while (delta) { idx = (idx + delta) & sizeMask; group = table->getCellGroups() + (idx >> 2); cell = group->cells + (idx & 3); Hash probeHash = cell->hash.load(Relaxed); // Note: probeHash might actually be NULL due to memory reordering of a concurrent insert, // but we don't check for it. We just follow the probe chain. if (probeHash == hash) { return cell; } delta = group->deltas[(idx & 3) + 4].load(Relaxed); } // End of probe chain, not found return NULL; } // FIXME: Possible optimization: Dedicated insert for migration? It wouldn't check for InsertResult_AlreadyFound. enum InsertResult { InsertResult_AlreadyFound, InsertResult_InsertedNew, InsertResult_Overflow }; static InsertResult insertOrFind(Hash hash, Table* table, Cell*& cell, quint64& overflowIdx) { Q_ASSERT(table); Q_ASSERT(hash != KeyTraits::NullHash); quint64 sizeMask = table->sizeMask; quint64 idx = quint64(hash); // Check hashed cell first, though it may not even belong to the bucket. CellGroup* group = table->getCellGroups() + ((idx & sizeMask) >> 2); cell = group->cells + (idx & 3); Hash probeHash = cell->hash.load(Relaxed); if (probeHash == KeyTraits::NullHash) { if (cell->hash.compareExchangeStrong(probeHash, hash, Relaxed)) { // There are no links to set. We're done. return InsertResult_InsertedNew; } else { // Fall through to check if it was the same hash... } } if (probeHash == hash) { return InsertResult_AlreadyFound; } // Follow the link chain for this bucket. quint64 maxIdx = idx + sizeMask; quint64 linkLevel = 0; Atomic* prevLink; for (;;) { followLink: prevLink = group->deltas + ((idx & 3) + linkLevel); linkLevel = 4; quint8 probeDelta = prevLink->load(Relaxed); if (probeDelta) { idx += probeDelta; // Check the hash for this cell. group = table->getCellGroups() + ((idx & sizeMask) >> 2); cell = group->cells + (idx & 3); probeHash = cell->hash.load(Relaxed); if (probeHash == KeyTraits::NullHash) { // Cell was linked, but hash is not visible yet. // We could avoid this case (and guarantee it's visible) using acquire & release, but instead, // just poll until it becomes visible. do { probeHash = cell->hash.load(Acquire); } while (probeHash == KeyTraits::NullHash); } Q_ASSERT(((probeHash ^ hash) & sizeMask) == 0); // Only hashes in same bucket can be linked if (probeHash == hash) { return InsertResult_AlreadyFound; } } else { // Reached the end of the link chain for this bucket. // Switch to linear probing until we reserve a new cell or find a late-arriving cell in the same bucket. quint64 prevLinkIdx = idx; Q_ASSERT(qint64(maxIdx - idx) >= 0); // Nobody would have linked an idx that's out of range. quint64 linearProbesRemaining = qMin(maxIdx - idx, quint64(LinearSearchLimit)); while (linearProbesRemaining-- > 0) { idx++; group = table->getCellGroups() + ((idx & sizeMask) >> 2); cell = group->cells + (idx & 3); probeHash = cell->hash.load(Relaxed); if (probeHash == KeyTraits::NullHash) { // It's an empty cell. Try to reserve it. if (cell->hash.compareExchangeStrong(probeHash, hash, Relaxed)) { // Success. We've reserved the cell. Link it to previous cell in same bucket. Q_ASSERT(probeDelta == 0); quint8 desiredDelta = idx - prevLinkIdx; prevLink->store(desiredDelta, Relaxed); return InsertResult_InsertedNew; } else { // Fall through to check if it's the same hash... } } Hash x = (probeHash ^ hash); // Check for same hash. if (!x) { return InsertResult_AlreadyFound; } // Check for same bucket. if ((x & sizeMask) == 0) { // Attempt to set the link on behalf of the late-arriving cell. // This is usually redundant, but if we don't attempt to set the late-arriving cell's link here, // there's no guarantee that our own link chain will be well-formed by the time this function returns. // (Indeed, subsequent lookups sometimes failed during testing, for this exact reason.) quint8 desiredDelta = idx - prevLinkIdx; prevLink->store(desiredDelta, Relaxed); goto followLink; // Try to follow link chain for the bucket again. } // Continue linear search... } // Table is too full to insert. overflowIdx = idx + 1; return InsertResult_Overflow; } } } static void beginTableMigrationToSize(Map& map, Table* table, quint64 nextTableSize) { // Create new migration by DCLI. SimpleJobCoordinator::Job* job = table->jobCoordinator.loadConsume(); if (job) { // new migration already exists } else { QMutexLocker guard(&table->mutex); job = table->jobCoordinator.loadConsume(); // Non-atomic would be sufficient, but that's OK. if (job) { // new migration already exists (double-checked) } else { // Create new migration. TableMigration* migration = TableMigration::create(map, 1); migration->m_unitsRemaining.storeNonatomic(table->getNumMigrationUnits()); migration->getSources()[0].table = table; migration->getSources()[0].sourceIndex.storeNonatomic(0); migration->m_destination = Table::create(nextTableSize); // Publish the new migration. table->jobCoordinator.storeRelease(migration); } } } static void beginTableMigration(Map& map, Table* table, quint64 overflowIdx) { // Estimate number of cells in use based on a small sample. quint64 sizeMask = table->sizeMask; quint64 idx = overflowIdx - CellsInUseSample; quint64 inUseCells = 0; for (quint64 linearProbesRemaining = CellsInUseSample; linearProbesRemaining > 0; linearProbesRemaining--) { CellGroup* group = table->getCellGroups() + ((idx & sizeMask) >> 2); Cell* cell = group->cells + (idx & 3); Value value = cell->value.load(Relaxed); if (value == Value(ValueTraits::Redirect)) { // Another thread kicked off the jobCoordinator. The caller will participate upon return. return; } if (value != Value(ValueTraits::NullValue)) inUseCells++; idx++; } float inUseRatio = float(inUseCells) / CellsInUseSample; float estimatedInUse = (sizeMask + 1) * inUseRatio; quint64 nextTableSize = qMax(quint64(InitialSize), roundUpPowerOf2(quint64(estimatedInUse * 2))); beginTableMigrationToSize(map, table, nextTableSize); } }; // Leapfrog template bool Leapfrog::TableMigration::migrateRange(Table* srcTable, quint64 startIdx) { quint64 srcSizeMask = srcTable->sizeMask; quint64 endIdx = qMin(startIdx + TableMigrationUnitSize, srcSizeMask + 1); // Iterate over source range. for (quint64 srcIdx = startIdx; srcIdx < endIdx; srcIdx++) { CellGroup* srcGroup = srcTable->getCellGroups() + ((srcIdx & srcSizeMask) >> 2); Cell* srcCell = srcGroup->cells + (srcIdx & 3); Hash srcHash; Value srcValue; // Fetch the srcHash and srcValue. for (;;) { srcHash = srcCell->hash.load(Relaxed); if (srcHash == KeyTraits::NullHash) { // An unused cell. Try to put a Redirect marker in its value. srcValue = srcCell->value.compareExchange(Value(ValueTraits::NullValue), Value(ValueTraits::Redirect), Relaxed); if (srcValue == Value(ValueTraits::Redirect)) { // srcValue is already marked Redirect due to previous incomplete migration. break; } if (srcValue == Value(ValueTraits::NullValue)) { break; // Redirect has been placed. Break inner loop, continue outer loop. } // Otherwise, somebody just claimed the cell. Read srcHash again... } else { // Check for deleted/uninitialized value. srcValue = srcCell->value.load(Relaxed); if (srcValue == Value(ValueTraits::NullValue)) { // Try to put a Redirect marker. if (srcCell->value.compareExchangeStrong(srcValue, Value(ValueTraits::Redirect), Relaxed)) { break; // Redirect has been placed. Break inner loop, continue outer loop. } if (srcValue == Value(ValueTraits::Redirect)) { // FIXME: I don't think this will happen. Investigate & change to assert break; } } else if (srcValue == Value(ValueTraits::Redirect)) { // srcValue is already marked Redirect due to previous incomplete migration. break; } // We've got a key/value pair to migrate. // Reserve a destination cell in the destination. Q_ASSERT(srcHash != KeyTraits::NullHash); Q_ASSERT(srcValue != Value(ValueTraits::NullValue)); Q_ASSERT(srcValue != Value(ValueTraits::Redirect)); Cell* dstCell; quint64 overflowIdx; InsertResult result = insertOrFind(srcHash, m_destination, dstCell, overflowIdx); // During migration, a hash can only exist in one place among all the source tables, // and it is only migrated by one thread. Therefore, the hash will never already exist // in the destination table: Q_ASSERT(result != InsertResult_AlreadyFound); if (result == InsertResult_Overflow) { // Destination overflow. // This can happen for several reasons. For example, the source table could have // existed of all deleted cells when it overflowed, resulting in a small destination // table size, but then another thread could re-insert all the same hashes // before the migration completed. // Caller will cancel the current migration and begin a new one. return false; } // Migrate the old value to the new cell. for (;;) { // Copy srcValue to the destination. dstCell->value.store(srcValue, Relaxed); // Try to place a Redirect marker in srcValue. Value doubleCheckedSrcValue = srcCell->value.compareExchange(srcValue, Value(ValueTraits::Redirect), Relaxed); Q_ASSERT(doubleCheckedSrcValue != Value(ValueTraits::Redirect)); // Only one thread can redirect a cell at a time. if (doubleCheckedSrcValue == srcValue) { // No racing writes to the src. We've successfully placed the Redirect marker. // srcValue was non-NULL when we decided to migrate it, but it may have changed to NULL // by a late-arriving erase. if (srcValue == Value(ValueTraits::NullValue)) { // racing update was erase", uptr(srcTable), srcIdx) } break; } // There was a late-arriving write (or erase) to the src. Migrate the new value and try again. srcValue = doubleCheckedSrcValue; } // Cell successfully migrated. Proceed to next source cell. break; } } } // Range has been migrated successfully. return true; } template void Leapfrog::TableMigration::run() { // Conditionally increment the shared # of workers. quint64 probeStatus = m_workerStatus.load(Relaxed); do { if (probeStatus & 1) { // End flag is already set, so do nothing. return; } } while (!m_workerStatus.compareExchangeWeak(probeStatus, probeStatus + 2, Relaxed, Relaxed)); // # of workers has been incremented, and the end flag is clear. Q_ASSERT((probeStatus & 1) == 0); // Iterate over all source tables. for (quint64 s = 0; s < m_numSources; s++) { Source& source = getSources()[s]; // Loop over all migration units in this source table. for (;;) { if (m_workerStatus.load(Relaxed) & 1) { goto endMigration; } quint64 startIdx = source.sourceIndex.fetchAdd(TableMigrationUnitSize, Relaxed); if (startIdx >= source.table->sizeMask + 1) break; // No more migration units in this table. Try next source table. bool overflowed = !migrateRange(source.table, startIdx); if (overflowed) { // *** FAILED MIGRATION *** // TableMigration failed due to destination table overflow. // No other thread can declare the migration successful at this point, because *this* unit will never complete, // hence m_unitsRemaining won't reach zero. // However, multiple threads can independently detect a failed migration at the same time. // The reason we store overflowed in a shared variable is because we can must flush all the worker threads before // we can safely deal with the overflow. Therefore, the thread that detects the failure is often different from // the thread // that deals with it. bool oldOverflowed = m_overflowed.exchange(overflowed, Relaxed); if (oldOverflowed) { // race to set m_overflowed } m_workerStatus.fetchOr(1, Relaxed); goto endMigration; } qint64 prevRemaining = m_unitsRemaining.fetchSub(1, Relaxed); Q_ASSERT(prevRemaining > 0); if (prevRemaining == 1) { // *** SUCCESSFUL MIGRATION *** // That was the last chunk to migrate. m_workerStatus.fetchOr(1, Relaxed); goto endMigration; } } } endMigration: // Decrement the shared # of workers. probeStatus = m_workerStatus.fetchSub(2, AcquireRelease); // AcquireRelease makes all previous writes visible to the last worker thread. if (probeStatus >= 4) { // There are other workers remaining. Return here so that only the very last worker will proceed. return; } // We're the very last worker thread. // Perform the appropriate post-migration step depending on whether the migration succeeded or failed. Q_ASSERT(probeStatus == 3); bool overflowed = m_overflowed.loadNonatomic(); // No racing writes at this point if (!overflowed) { // The migration succeeded. This is the most likely outcome. Publish the new subtree. m_map.publishTableMigration(this); // End the jobCoodinator. getSources()[0].table->jobCoordinator.end(); } else { // The migration failed due to the overflow of the destination table. Table* origTable = getSources()[0].table; QMutexLocker guard(&origTable->mutex); SimpleJobCoordinator::Job* checkedJob = origTable->jobCoordinator.loadConsume(); if (checkedJob != this) { // a new TableMigration was already started } else { TableMigration* migration = TableMigration::create(m_map, m_numSources + 1); // Double the destination table size. migration->m_destination = Table::create((m_destination->sizeMask + 1) * 2); // Transfer source tables to the new migration. for (quint64 i = 0; i < m_numSources; i++) { migration->getSources()[i].table = getSources()[i].table; getSources()[i].table = NULL; migration->getSources()[i].sourceIndex.storeNonatomic(0); } migration->getSources()[m_numSources].table = m_destination; migration->getSources()[m_numSources].sourceIndex.storeNonatomic(0); // Calculate total number of migration units to move. quint64 unitsRemaining = 0; for (quint64 s = 0; s < migration->m_numSources; s++) { unitsRemaining += migration->getSources()[s].table->getNumMigrationUnits(); } migration->m_unitsRemaining.storeNonatomic(unitsRemaining); // Publish the new migration. origTable->jobCoordinator.storeRelease(migration); } } // We're done with this TableMigration. Queue it for GC. - m_map.getGC().enqueue(&TableMigration::destroy, this); +// m_map.getGC().enqueue(this); } #endif // LEAPFROG_H diff --git a/libs/image/3rdparty/lock_free_map/qsbr.h b/libs/image/3rdparty/lock_free_map/qsbr.h index f023579a97..a3b3b9071e 100644 --- a/libs/image/3rdparty/lock_free_map/qsbr.h +++ b/libs/image/3rdparty/lock_free_map/qsbr.h @@ -1,192 +1,274 @@ /*------------------------------------------------------------------------ Junction: Concurrent data structures in C++ Copyright (c) 2016 Jeff Preshing Distributed under the Simplified BSD License. Original location: https://github.com/preshing/junction This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE file for more information. ------------------------------------------------------------------------*/ #ifndef QSBR_H #define QSBR_H #include #include #include #define CALL_MEMBER(obj, pmf) ((obj).*(pmf)) +struct Property { + Property() = default; + virtual ~Property() = default; +}; + +template +class GarbageCollector +{ +public: + ~GarbageCollector() + { + cleanUpNodes(); + } + + void enqueue(T *data) + { + m_rawPointerUsers.ref(); + + Node *newNode = new Node(data); + Node *head; + + do { + head = m_freeNodes.loadAcquire(); + newNode->next = head; + } while (!m_freeNodes.testAndSetRelease(head, newNode)); + + m_rawPointerUsers.deref(); + } + + void update() + { + m_rawPointerUsers.ref(); + + if (m_rawPointerUsers == 1) { + Node *head = m_freeNodes.loadAcquire(); + if (!(reinterpret_cast(head) & 1)) { + if (m_freeNodes.testAndSetOrdered(head, reinterpret_cast(reinterpret_cast(head) | 1))) { + if (m_rawPointerUsers == 1) { + if (m_freeNodes.testAndSetOrdered(reinterpret_cast(reinterpret_cast(head) | 1), 0)) { + cleanUpNodes(); + } + } else { + m_freeNodes.testAndSetOrdered(reinterpret_cast(reinterpret_cast(head) | 1), head); + } + } + } + } + + m_rawPointerUsers.deref(); + } + +private: + struct Node { + Node(T *data) : d(data) {} + + Node *next; + T* d; + }; + + inline void cleanUpNodes() + { + Node *head = m_freeNodes.fetchAndStoreOrdered(0); + if (head) { + freeList(head); + } + } + + inline void freeList(Node *first) + { + Node *next; + while (first) { + next = first->next; + delete first; + first = next; + } + } + +private: + QAtomicInt m_rawPointerUsers; + QAtomicPointer m_freeNodes; +}; + class QSBR { private: struct Action { void (*func)(void*); quint64 param[4]; // Size limit found experimentally. Verified by assert below. Action() = default; Action(void (*f)(void*), void* p, quint64 paramSize) : func(f) { Q_ASSERT(paramSize <= sizeof(param)); // Verify size limit. memcpy(¶m, p, paramSize); } void operator()() { func(¶m); } }; struct Status { qint16 inUse : 1; qint16 wasIdle : 1; qint16 nextFree : 14; Status() : inUse(1), wasIdle(0), nextFree(0) { } }; QMutex m_mutex; QVector m_status; qint64 m_freeIndex; qint64 m_numContexts; qint64 m_remaining; QVector m_deferredActions; QVector m_pendingActions; void onAllQuiescentStatesPassed(QVector& actions) { // m_mutex must be held actions.swap(m_pendingActions); m_pendingActions.swap(m_deferredActions); m_remaining = m_numContexts; for (qint32 i = 0; i < m_status.size(); i++) { m_status[i].wasIdle = 0; } } public: typedef qint16 Context; QSBR() : m_freeIndex(-1), m_numContexts(0), m_remaining(0) { } Context createContext() { QMutexLocker guard(&m_mutex); m_numContexts++; m_remaining++; Q_ASSERT(m_numContexts < (1 << 14)); qint64 context = m_freeIndex; if (context >= 0) { Q_ASSERT(context < (qint64) m_status.size()); Q_ASSERT(!m_status[context].inUse); m_freeIndex = m_status[context].nextFree; m_status[context] = Status(); } else { context = m_status.size(); m_status.append(Status()); } return context; } void destroyContext(QSBR::Context context) { QVector actions; { QMutexLocker guard(&m_mutex); Q_ASSERT(context < m_status.size()); if (m_status[context].inUse && !m_status[context].wasIdle) { Q_ASSERT(m_remaining > 0); --m_remaining; } m_status[context].inUse = 0; m_status[context].nextFree = m_freeIndex; m_freeIndex = context; m_numContexts--; if (m_remaining == 0) { onAllQuiescentStatesPassed(actions); } } for (qint32 i = 0; i < actions.size(); i++) { actions[i](); } } template void enqueue(void (T::*pmf)(), T* target) { struct Closure { void (T::*pmf)(); T* target; static void thunk(void* param) { Closure* self = (Closure*) param; CALL_MEMBER(*self->target, self->pmf)(); } }; Closure closure = {pmf, target}; QMutexLocker guard(&m_mutex); m_deferredActions.append(Action(Closure::thunk, &closure, sizeof(closure))); } void update(QSBR::Context context) { QVector actions; { QMutexLocker guard(&m_mutex); Q_ASSERT(context < m_status.size()); Status& status = m_status[context]; Q_ASSERT(status.inUse); if (status.wasIdle) { return; } status.wasIdle = 1; Q_ASSERT(m_remaining > 0); if (--m_remaining > 0) { return; } onAllQuiescentStatesPassed(actions); } for (qint32 i = 0; i < actions.size(); i++) { actions[i](); } } void flush() { // This is like saying that all contexts are quiescent, // so we can issue all actions at once. // No lock is taken. for (qint32 i = 0; i < m_pendingActions.size(); i++) { m_pendingActions[i](); } m_pendingActions.clear(); for (qint32 i = 0; i < m_deferredActions.size(); i++) { m_deferredActions[i](); } m_deferredActions.clear(); m_remaining = m_numContexts; } }; #endif // QSBR_H diff --git a/libs/image/tiles3/kis_tile_hash_table2.h b/libs/image/tiles3/kis_tile_hash_table2.h index c97a426813..2c745dcf4e 100644 --- a/libs/image/tiles3/kis_tile_hash_table2.h +++ b/libs/image/tiles3/kis_tile_hash_table2.h @@ -1,395 +1,361 @@ #ifndef KIS_TILEHASHTABLE_2_H #define KIS_TILEHASHTABLE_2_H #include "kis_shared.h" #include "kis_shared_ptr.h" #include "3rdparty/lock_free_map/concurrent_map.h" +#include "kis_lockless_stack.h" #include "kis_tile.h" - #include template class KisTileHashTableTraits2 { static constexpr bool isInherited = std::is_convertible::value; Q_STATIC_ASSERT_X(isInherited, "Template must inherit KisShared"); public: typedef T TileType; typedef KisSharedPtr TileTypeSP; typedef KisWeakSharedPtr TileTypeWSP; KisTileHashTableTraits2(); KisTileHashTableTraits2(KisMementoManager *mm); KisTileHashTableTraits2(const KisTileHashTableTraits2 &ht, KisMementoManager *mm); ~KisTileHashTableTraits2(); TileTypeSP insert(quint32 key, TileTypeSP value) { - m_rawPointerUsers.fetchAndAddRelaxed(1); TileTypeSP::ref(&value, value.data()); TileType *result = m_map.assign(key, value.data()); if (result) { - MemoryReclaimer *tmp = new MemoryReclaimer(result); - m_map.getGC().enqueue(&MemoryReclaimer::destroy, tmp); + m_map.getGC().enqueue(new MemoryReclaimer(result)); } else { m_numTiles.fetchAndAddRelaxed(1); } - m_rawPointerUsers.fetchAndSubRelaxed(1); +// m_map.getGC().update(); return TileTypeSP(result); } TileTypeSP erase(quint32 key) { - m_rawPointerUsers.fetchAndAddRelaxed(1); TileType *result = m_map.erase(key); TileTypeSP ptr(result); if (result) { m_numTiles.fetchAndSubRelaxed(1); - MemoryReclaimer *tmp = new MemoryReclaimer(result); - m_map.getGC().enqueue(&MemoryReclaimer::destroy, tmp); - } - - if (m_rawPointerUsers == 1) { - m_map.getGC().update(m_context); + m_map.getGC().enqueue(new MemoryReclaimer(result)); } - m_rawPointerUsers.fetchAndSubRelaxed(1); +// m_map.getGC().update(); return ptr; } TileTypeSP get(quint32 key) { - m_rawPointerUsers.fetchAndAddRelaxed(1); TileTypeSP result(m_map.get(key)); - - if (m_rawPointerUsers == 1) { - m_map.getGC().update(m_context); - } - - m_rawPointerUsers.fetchAndSubRelaxed(1); +// m_map.getGC().update(); return result; } - TileTypeSP getLazy(quint32 key, TileTypeSP value, bool &newTile) - { - m_rawPointerUsers.fetchAndAddRelaxed(1); - newTile = false; - TileType *tile; - typename ConcurrentMap::Mutator mutator = m_map.insertOrFind(key); - - if (!mutator.getValue()) { - TileTypeSP::ref(&value, value.data()); - TileType *result = mutator.exchangeValue(value.data()); - - if (result) { - MemoryReclaimer *tmp = new MemoryReclaimer(result); - m_map.getGC().enqueue(&MemoryReclaimer::destroy, tmp); - } else { - m_numTiles.fetchAndAddRelaxed(1); - } - - newTile = true; - tile = m_map.get(key); - } else { - tile = mutator.getValue(); - } - - if (m_rawPointerUsers == 1) { - m_map.getGC().update(m_context); - } - - m_rawPointerUsers.fetchAndSubRelaxed(1); - return TileTypeSP(tile); - } - bool isEmpty() { - return !m_numTiles; + return !m_numTiles.load(); } bool tileExists(qint32 col, qint32 row); /** * Returns a tile in position (col,row). If no tile exists, * returns null. * \param col column of the tile * \param row row of the tile */ TileTypeSP getExistingTile(qint32 col, qint32 row); /** * Returns a tile in position (col,row). If no tile exists, * creates a new one, attaches it to the list and returns. * \param col column of the tile * \param row row of the tile * \param newTile out-parameter, returns true if a new tile * was created */ TileTypeSP getTileLazy(qint32 col, qint32 row, bool& newTile); /** * Returns a tile in position (col,row). If no tile exists, * creates nothing, but returns shared default tile object * of the table. Be careful, this object has column and row * parameters set to (qint32_MIN, qint32_MIN). * \param col column of the tile * \param row row of the tile * \param existingTile returns true if the tile actually exists in the table * and it is not a lazily created default wrapper tile */ TileTypeSP getReadOnlyTileLazy(qint32 col, qint32 row, bool &existingTile); void addTile(TileTypeSP tile); bool deleteTile(TileTypeSP tile); bool deleteTile(qint32 col, qint32 row); void clear(); void setDefaultTileData(KisTileData *defaultTileData); - KisTileData* defaultTileData() const; + KisTileData* defaultTileData(); qint32 numTiles() { - return m_numTiles; + return m_numTiles.load(); } void debugPrintInfo(); void debugMaxListLength(qint32 &min, qint32 &max); ConcurrentMap &map() { return m_map; } private: static inline quint32 calculateHash(qint32 col, qint32 row); - struct MemoryReclaimer { + struct MemoryReclaimer : public Property { MemoryReclaimer(TileType *data) : d(data) {} - ~MemoryReclaimer() = default; - - void destroy() + ~MemoryReclaimer() { TileTypeSP::deref(reinterpret_cast(this), d); - this->MemoryReclaimer::~MemoryReclaimer(); - delete this; } private: TileType *d; }; private: ConcurrentMap m_map; - QSBR::Context m_context; - QAtomicInt m_rawPointerUsers; QAtomicInt m_numTiles; QReadWriteLock m_rwLock; + KisLocklessStack m_stack; KisTileData *m_defaultTileData; KisMementoManager *m_mementoManager; }; template class KisTileHashTableIteratorTraits2 { public: typedef T TileType; typedef KisSharedPtr TileTypeSP; typedef typename ConcurrentMap::Iterator Iterator; KisTileHashTableIteratorTraits2(KisTileHashTableTraits2 *ht) : m_ht(ht) { m_iter.setMap(m_ht->map()); } void next() { m_iter.next(); } TileTypeSP tile() const { - return m_iter.getValue(); + return TileTypeSP(m_iter.getValue()); } bool isDone() const { return !m_iter.isValid(); } void deleteCurrent() { m_ht->erase(m_iter.getKey()); next(); } void moveCurrentToHashTable(KisTileHashTableTraits2 *newHashTable) { TileTypeSP tile = m_iter.getValue(); next(); m_ht->deleteTile(tile); newHashTable->addTile(tile); } private: KisTileHashTableTraits2 *m_ht; typename ConcurrentMap::Iterator m_iter; }; template KisTileHashTableTraits2::KisTileHashTableTraits2() - : m_rawPointerUsers(0), m_numTiles(0), - m_defaultTileData(0), m_mementoManager(0) + : m_numTiles(0), m_rwLock(QReadWriteLock::NonRecursive), m_defaultTileData(0), m_mementoManager(0) { - m_context = m_map.getGC().createContext(); } template KisTileHashTableTraits2::KisTileHashTableTraits2(KisMementoManager *mm) : KisTileHashTableTraits2() { m_mementoManager = mm; } template KisTileHashTableTraits2::KisTileHashTableTraits2(const KisTileHashTableTraits2 &ht, KisMementoManager *mm) : KisTileHashTableTraits2(mm) { setDefaultTileData(ht.m_defaultTileData); typename ConcurrentMap::Iterator iter(const_cast &>(ht.m_map)); while (iter.isValid()) { insert(iter.getKey(), iter.getValue()); iter.next(); } } template KisTileHashTableTraits2::~KisTileHashTableTraits2() { - clear(); - m_map.getGC().destroyContext(m_context); +// clear(); } template bool KisTileHashTableTraits2::tileExists(qint32 col, qint32 row) { return get(calculateHash(col, row)) != nullptr; } template typename KisTileHashTableTraits2::TileTypeSP KisTileHashTableTraits2::getExistingTile(qint32 col, qint32 row) { quint32 idx = calculateHash(col, row); return get(idx); } template typename KisTileHashTableTraits2::TileTypeSP KisTileHashTableTraits2::getTileLazy(qint32 col, qint32 row, bool &newTile) { + newTile = false; TileTypeSP tile; - { - QReadLocker guard(&m_rwLock); - tile = new TileType(col, row, m_defaultTileData, m_mementoManager); - } quint32 idx = calculateHash(col, row); - return getLazy(idx, tile, newTile); + typename ConcurrentMap::Mutator mutator = m_map.insertOrFind(idx); + + if (!mutator.getValue()) { + { + QReadLocker guard(&m_rwLock); + tile = new TileType(col, row, m_defaultTileData, m_mementoManager); + } + TileTypeSP::ref(&tile, tile.data()); + TileType *result = mutator.exchangeValue(tile.data()); + + if (result) { + m_map.getGC().enqueue(new MemoryReclaimer(result)); + } else { + m_numTiles.fetchAndAddRelaxed(1); + } + + newTile = true; + tile = m_map.get(idx); + } else { + tile = mutator.getValue(); + } + +// m_map.getGC().update(); + return tile; } template typename KisTileHashTableTraits2::TileTypeSP KisTileHashTableTraits2::getReadOnlyTileLazy(qint32 col, qint32 row, bool &existingTile) { - m_rawPointerUsers.fetchAndAddRelaxed(1); quint32 idx = calculateHash(col, row); TileTypeSP tile(m_map.get(idx)); existingTile = tile; if (!existingTile) { QReadLocker guard(&m_rwLock); tile = new TileType(col, row, m_defaultTileData, 0); } - m_rawPointerUsers.fetchAndSubRelaxed(1); +// m_map.getGC().update(); return tile; } template void KisTileHashTableTraits2::addTile(TileTypeSP tile) { quint32 idx = calculateHash(tile->col(), tile->row()); insert(idx, tile); } template bool KisTileHashTableTraits2::deleteTile(TileTypeSP tile) { return deleteTile(tile->col(), tile->row()); } template bool KisTileHashTableTraits2::deleteTile(qint32 col, qint32 row) { quint32 idx = calculateHash(col, row); return erase(idx) != 0; } template void KisTileHashTableTraits2::clear() { typename ConcurrentMap::Iterator iter(m_map); while (iter.isValid()) { erase(iter.getKey()); iter.next(); } } template inline void KisTileHashTableTraits2::setDefaultTileData(KisTileData *defaultTileData) { QWriteLocker guard(&m_rwLock); if (m_defaultTileData) { m_defaultTileData->release(); m_defaultTileData = 0; } if (defaultTileData) { defaultTileData->acquire(); m_defaultTileData = defaultTileData; } } template -inline KisTileData* KisTileHashTableTraits2::defaultTileData() const +inline KisTileData* KisTileHashTableTraits2::defaultTileData() { + QReadLocker guard(&m_rwLock); return m_defaultTileData; } template void KisTileHashTableTraits2::debugPrintInfo() { } template void KisTileHashTableTraits2::debugMaxListLength(qint32 &min, qint32 &max) { } template quint32 KisTileHashTableTraits2::calculateHash(qint32 col, qint32 row) { std::size_t seed = 0; boost::hash_combine(seed, col); boost::hash_combine(seed, row); return seed; // return (((row << 5) + (col & 0x1F)) & 0x3FF) + 1; } typedef KisTileHashTableTraits2 KisTileHashTable; typedef KisTileHashTableIteratorTraits2 KisTileHashTableIterator; typedef KisTileHashTableIteratorTraits2 KisTileHashTableConstIterator; #endif // KIS_TILEHASHTABLE_2_H diff --git a/libs/image/tiles3/tests/kis_lock_free_map_test.cpp b/libs/image/tiles3/tests/kis_lock_free_map_test.cpp index a87087ee2f..a77666bf2d 100644 --- a/libs/image/tiles3/tests/kis_lock_free_map_test.cpp +++ b/libs/image/tiles3/tests/kis_lock_free_map_test.cpp @@ -1,188 +1,125 @@ #include "kis_lock_free_map_test.h" #include #include "kis_debug.h" #include "tiles3/kis_memento_item.h" #include "tiles3/kis_tile_hash_table2.h" #define NUM_THREADS 10 class Wrapper : public KisShared { public: Wrapper() : m_member(0) {} Wrapper(qint32 col, qint32 row, KisTileData *defaultTileData, KisMementoManager* mm) : m_member(col) {} qint32 member() { return m_member; } private: qint32 m_member; }; class StressJob : public QRunnable { public: StressJob(const std::function func) : m_func(func), m_eraseSum(0), m_insertSum(0) { } qint64 eraseSum() { return m_eraseSum; } qint64 insertSum() { return m_insertSum; } protected: void run() override { m_func(m_eraseSum, m_insertSum); } private: const std::function m_func; qint64 m_eraseSum; qint64 m_insertSum; }; void LockFreeMapTest::testMainOperations() { const qint32 numCycles = 60000; const qint32 numTypes = 3; QList jobs; KisTileHashTableTraits2 map; auto func = [&](qint64 & eraseSum, qint64 & insertSum) { for (qint32 i = 1; i < numCycles + 1; ++i) { auto type = i % numTypes; switch (type) { case 0: { auto result = map.erase(i - 2); if (result.data()) { eraseSum += result->member(); } break; } case 1: { auto result = map.insert(i, KisSharedPtr(new Wrapper(i, 0, 0, 0))); if (result.data()) { insertSum -= result->member(); } insertSum += i; break; } case 2: { map.get(i - 1); break; } } } }; for (qint32 i = 0; i < NUM_THREADS; ++i) { StressJob *job = new StressJob(func); job->setAutoDelete(false); jobs.append(job); } QThreadPool pool; pool.setMaxThreadCount(NUM_THREADS); QBENCHMARK { for (auto &job : jobs) { pool.start(job); } pool.waitForDone(); } qint64 insertSum = 0; qint64 eraseSum = 0; for (qint32 i = 0; i < NUM_THREADS; ++i) { StressJob *job = jobs.takeLast(); eraseSum += job->eraseSum(); insertSum += job->insertSum(); delete job; } QVERIFY(insertSum == eraseSum); } -void LockFreeMapTest::testLazy() -{ - const qint32 numCycles = 50000; - const qint32 numTypes = 2; - QList jobs; - KisTileHashTableTraits2 map; - - auto func = [&](qint64 & eraseSum, qint64 & insertSum) { - for (qint32 i = 1; i < numCycles + 1; ++i) { - auto type = i % numTypes; - - switch (type) { - case 0: { - auto result = map.erase(i - 1); - if (result.data()) { - eraseSum += result->member(); - } - break; - } - case 1: { - bool newTile = false; - auto result = map.getLazy(i, KisSharedPtr(new Wrapper()), newTile); - if (result.data()) { - insertSum += result->member(); - } - break; - } - } - } - }; - - for (qint32 i = 0; i < NUM_THREADS; ++i) { - StressJob *job = new StressJob(func); - job->setAutoDelete(false); - jobs.append(job); - } - - QThreadPool pool; - pool.setMaxThreadCount(NUM_THREADS); - - QBENCHMARK { - for (auto &job : jobs) - { - pool.start(job); - } - - pool.waitForDone(); - } - - qint64 insertSum = 0; - qint64 eraseSum = 0; - - for (qint32 i = 0; i < NUM_THREADS; ++i) { - StressJob *job = jobs.takeLast(); - eraseSum += job->eraseSum(); - insertSum += job->insertSum(); - - delete job; - } - - QVERIFY(insertSum == eraseSum); -} - QTEST_GUILESS_MAIN(LockFreeMapTest)