コード例 #1
0
ファイル: Matrix.cpp プロジェクト: pthibaud/MicroMagnum
void Matrix::randomize()
{
    const int dev = computeStrategy1();
    writeLock(dev);
    matty::getDevice(dev)->randomize(getArray(dev));
    writeUnlock(dev);
}
コード例 #2
0
bool
MM_HeapRegionManagerTarok::setContiguousHeapRange(MM_EnvironmentBase *env, void *lowHeapEdge, void *highHeapEdge)
{
	writeLock();
	/* ensure that this manager was configured with a valid region size */
	Assert_MM_true(0 != _regionSize);
	/* we don't yet support multiple enabling calls (split heaps) */
	/* This assertion would triggered at multiple attempts to initialize heap in gcInitializeDefaults() */
	/* Assert_MM_true(NULL == _regionTable); */
	/* the regions must be aligned (in present implementation) */
	Assert_MM_true(0 == ((uintptr_t)lowHeapEdge % _regionSize));
	Assert_MM_true(0 == ((uintptr_t)highHeapEdge % _regionSize));
	/* make sure that the range is in the right order and of non-zero size*/
	Assert_MM_true(highHeapEdge > lowHeapEdge);
	/* allocate the table */
	uintptr_t size = (uintptr_t)highHeapEdge - (uintptr_t)lowHeapEdge;
	_tableRegionCount = size / _regionSize;
	_regionTable = internalAllocateAndInitializeRegionTable(env, lowHeapEdge, highHeapEdge);
	bool success = false;
	if (NULL != _regionTable) {
		_lowTableEdge = lowHeapEdge;
		_highTableEdge = highHeapEdge;
		success = true;
	}
	writeUnlock();
	return success;
}
コード例 #3
0
static skipItem skipLock(skipList list, UINT32 key, skipItem *save, INT32 top) {

  INT32 i;
  skipItem x, y;

  if(list->threaded)
    readLock(list);

  x = list->header;                            /* header contains all levels */

  for(i = top;                        /* loop from top level down to level 0 */
      i >= 0;
      i--) {

    y = x->next[i];                           /* get next item at this level */

    while(y->key < key) {       /* if y has a smaller key, try the next item */
      x = y;                                  /* save x in case we overshoot */
      y = x->next[i];                                       /* get next item */
    }

    save[i] = x;                  /* preserve item with next pointer in save */
  }

  if(list->threaded)
    writeLock(list);                                 /* lock list for update */

                               /* validate we have the closest previous item */
  return skipClosest(x, key, 0);
}
コード例 #4
0
 bool upload(void* image, int width, int height) {
     if(!writeLock()) return false;
     metadata->timestamp = get_precise_time();
     memcpy(pixels, image, width * height * 4);
     writeUnlock();
     return true;
 }
コード例 #5
0
ファイル: TerrainCache.cpp プロジェクト: Marott1/Core3
void TerrainCache::clear(TerrainGenerator* generator) {
	float centerX, centerY, radius;

	bool result = generator->getFullBoundaryCircle(centerX, centerY, radius);

	//assert(result);

	if (!result)
		return;

	Vector<QuadTreeEntryInterface*> heightsToDelete;

	Locker writeLock(getLock());

	++clearCount;

	clearHeightsCount += quadTree.inRange(centerX, centerY, radius, heightsToDelete);

	for (int i = 0; i < heightsToDelete.size(); ++i) {
		HeightQuadTreeEntry* entry = static_cast<HeightQuadTreeEntry*>(heightsToDelete.get(i));

		remove(entry->getObjectID());

		quadTree.remove(entry);

		delete entry;
	}
}
コード例 #6
0
 bool StubFactoryRegistry::removeStubFactory(
     const std::string &objectName)
 {
     WriteLock writeLock(mStubFactoryMapMutex);
     mStubFactoryMap.erase(mStubFactoryMap.find(objectName));
     return true;
 }
コード例 #7
0
void
Printer::wait() {
	std::unique_lock<std::mutex> writeLock(writeMutex);
	while(commandQueue.size() > 0) {
		signalNextCommand.wait(writeLock);
	}
}
コード例 #8
0
ファイル: repl_set_impl.cpp プロジェクト: Rockyit/mongo
    bool ReplSetImpl::setMaintenanceMode(OperationContext* txn, const bool inc) {
        lock replLock(this);

        // Lock here to prevent state from changing between checking the state and changing it
        Lock::GlobalWrite writeLock(txn->lockState());

        if (box.getState().primary()) {
            return false;
        }

        if (inc) {
            log() << "replSet going into maintenance mode (" << _maintenanceMode
                  << " other tasks)" << rsLog;

            _maintenanceMode++;
            changeState(MemberState::RS_RECOVERING);
        }
        else if (_maintenanceMode > 0) {
            _maintenanceMode--;
            // no need to change state, syncTail will try to go live as a secondary soon

            log() << "leaving maintenance mode (" << _maintenanceMode << " other tasks)" << rsLog;
        }
        else {
            return false;
        }

        fassert(16844, _maintenanceMode >= 0);
        return true;
    }
コード例 #9
0
ファイル: Reporting.cpp プロジェクト: electrum/wdt
TransferStats& TransferStats::operator+=(const TransferStats& stats) {
  folly::RWSpinLock::WriteHolder writeLock(mutex_.get());
  folly::RWSpinLock::ReadHolder readLock(stats.mutex_.get());
  headerBytes_ += stats.headerBytes_;
  dataBytes_ += stats.dataBytes_;
  effectiveHeaderBytes_ += stats.effectiveHeaderBytes_;
  effectiveDataBytes_ += stats.effectiveDataBytes_;
  numFiles_ += stats.numFiles_;
  numBlocks_ += stats.numBlocks_;
  failedAttempts_ += stats.failedAttempts_;
  if (stats.errCode_ != OK) {
    if (errCode_ == OK) {
      // First error. Setting this as the error code
      errCode_ = stats.errCode_;
    } else if (stats.errCode_ != errCode_) {
      // Different error than the previous one. Setting error code as generic
      // ERROR
      errCode_ = ERROR;
    }
  }
  if (stats.remoteErrCode_ != OK) {
    if (remoteErrCode_ == OK) {
      remoteErrCode_ = stats.remoteErrCode_;
    } else if (stats.remoteErrCode_ != remoteErrCode_) {
      remoteErrCode_ = ERROR;
    }
  }
  return *this;
}
コード例 #10
0
ShTimeStream::~ShTimeStream()
{
    boost::upgrade_lock<boost::shared_mutex> lock(mutex);
    boost::upgrade_to_unique_lock<boost::shared_mutex> writeLock(lock);

    std::list<ShTimeEvent*>::iterator eventIter = timeEvents.begin();

    while(eventIter != timeEvents.end())
    {
        delete *eventIter;
        ++eventIter;
    }

    timeEvents.clear();

    std::list<ShTimeStream*>::iterator branchIter = timeBranches.begin();

    while(branchIter != timeBranches.end())
    {
        delete *branchIter;
        ++branchIter;
    }

    timeBranches.clear();
}
コード例 #11
0
ファイル: HashContainer.cpp プロジェクト: pantuspavel/hash
void HashContainer::insert(const string& key, double val, bool withTimeMeasPrintout)
{
	HashContainer::TimePoint tStart;
	if(withTimeMeasPrintout)
		tStart = boost::chrono::high_resolution_clock::now();

	unsigned int hashIndex = hash(key);
	SharedMutex* lock = bucketLocker[hashIndex];
	WriteLock writeLock(*lock);

	Element* el = bucket[hashIndex];

	if(el)
	{
		updateOrAppend(el, key, val);
	}
	else
	{
		Element* newEl = new Element();
		newEl->setKey(key);
		newEl->setValue(val);
		bucket[hashIndex] = newEl;
	}

	WriteLock valuesWriteLock(valuesLocker);
	values.insert(val);

	if(withTimeMeasPrintout)
	{
		HashContainer::TimePoint tFinish = boost::chrono::high_resolution_clock::now();
		std::cout << "Inserting el with key = " << key << "; val = " << val << " took " << boost::chrono::duration_cast<boost::chrono::microseconds>(tFinish - tStart).count() << " microseconds\n";
	}
}
コード例 #12
0
ファイル: PluginXmlParser.cpp プロジェクト: LordGaav/sipxecs
///////////////////////////PRIVATE///////////////////////////////////
void
PluginXmlParser::addPluginToList(StatusPluginReference* pluginContainer)
{
    OsWriteLock writeLock(mListMutexW);

    mPluginTable.insert(pluginContainer);
}
コード例 #13
0
ShTimeStream* ShTimeStream::addTimeEvent(ShTimeEvent* timeEvent)
{
    boost::upgrade_lock<boost::shared_mutex> lock(mutex);
    boost::upgrade_to_unique_lock<boost::shared_mutex> writeLock(lock);

    boost::chrono::steady_clock::time_point newTime = timeEvent->getTimeStamp();

    if(timeEvents.size() == 0)
    {
        timeEvents.push_back(timeEvent); // if new event time after last event time, push event onto the back
        currentEventIter = timeEvents.begin();
        updateTimeVars(newTime);
    }

    else if(newTime >= timeEvents.back()->getTimeStamp())
    {
        timeEvents.push_back(timeEvent); // if new event time after last event time, push event onto the back
        currentEventIter = timeEvents.end();
        --currentEventIter;
        updateTimeVars(newTime);
        return this;
    }

    else // Create a new branch
    {
        std::list<ShTimeStream*>::iterator streamIter = timeBranches.begin();
        std::stringstream newID;
        newID << id << "|" << timeBranches.size();

        /*
        while(streamIter != timeBranches.end())
        {
            if(newTime < (*streamIter)->getCreationTime())
            {
                if(streamIter != timeBranches.begin())
                {
                    ShTimeStream* stream = new ShTimeStream(newID.str(), newTime, this, createTimeSlice(newTime));
                    stream->addTimeEvent(timeEvent);
                    timeBranches.insert(streamIter, stream);
                    return stream;
                }

                else
                {
                    ShTimeStream* stream = new ShTimeStream(newID.str(), newTime, this, createTimeSlice(newTime));
                    stream->addTimeEvent(timeEvent);
                    timeBranches.push_front(stream);
                    return stream;
                }
            }

            ++streamIter;
        }*/

        ShTimeStream* stream = new ShTimeStream(newID.str(), newTime, this, createTimeSlice(newTime));
        stream->addTimeEvent(timeEvent);
        timeBranches.push_back(stream);
        return stream;
    }
}
コード例 #14
0
ファイル: DNS.cpp プロジェクト: 12307/poco
void DNS::reload()
{
#if defined(POCO_HAVE_LIBRESOLV)
	Poco::ScopedWriteRWLock writeLock(resolverLock);
	res_init();
#endif
}
コード例 #15
0
    void I_IpServerTransport::setAllowedClientIps(
        const std::vector<std::string> &allowedClientIps)
    {
        WriteLock writeLock(mReadWriteMutex);
        mAllowedIps.assign(allowedClientIps.begin(), allowedClientIps.end());

        // translate the ips into 32 bit values, network order
        mAllowedAddrs.clear();
        for (unsigned int i=0; i<mAllowedIps.size(); i++)
        {
            const std::string &ip = mAllowedIps[i];
            hostent *hostDesc = ::gethostbyname( ip.c_str() );
            if (hostDesc == NULL)
            {
                int err = Platform::OS::BsdSockets::GetLastError();
                std::string strErr = Platform::OS::GetErrorString(err);
                RCF_TRACE("gethostbyname() failed")(ip)(err)(strErr);
                mAllowedAddrs.push_back(INADDR_NONE);
            }
            else
            {
                in_addr addr = *((in_addr*) hostDesc->h_addr_list[0]);
                mAllowedAddrs.push_back(addr.s_addr);
            }
        }
    }
コード例 #16
0
void SReadArray::updating() throw( ::fwTools::Failed )
{
    ::fwData::Array::sptr array = this->getObject< ::fwData::Array >();
    ::fwData::mt::ObjectWriteLock writeLock(array);
    SLM_ASSERT("No array.", array);

    const int arraySize = 10;

    ::fwData::Array::SizeType size(1, arraySize);

    array->resize("uint32", size, 1, true);

    ::fwComEd::helper::Array arrayHelper(array);

    unsigned int *buffer = static_cast< unsigned int* >( arrayHelper.getBuffer() );

    for (int i = 0 ; i < arraySize; i++)
    {
        buffer[i] = i;
    }

    ::fwData::Object::ObjectModifiedSignalType::sptr sig
        = array->signal< ::fwData::Object::ObjectModifiedSignalType>( ::fwData::Object::s_OBJECT_MODIFIED_SIG );

    ::fwServices::ObjectMsg::sptr msg = ::fwServices::ObjectMsg::New();
    msg->addEvent("MODIFIED_EVENT");
    sig->asyncEmit(msg);
}
コード例 #17
0
/*
 * Install a new translator from file
 */
bool lamexp_install_translator_from_file(const QString &qmFile)
{
	QWriteLocker writeLock(&g_lamexp_currentTranslator.lock);
	bool success = false;

	if(!g_lamexp_currentTranslator.instance)
	{
		g_lamexp_currentTranslator.instance = new QTranslator();
	}

	if(!qmFile.isEmpty())
	{
		QString qmPath = QFileInfo(qmFile).canonicalFilePath();
		QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
		if(success = g_lamexp_currentTranslator.instance->load(qmPath))
		{
			QApplication::installTranslator(g_lamexp_currentTranslator.instance);
		}
		else
		{
			qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
		}
	}
	else
	{
		QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
		success = true;
	}

	return success;
}
コード例 #18
0
ファイル: repl_set_impl.cpp プロジェクト: JsonRuby/mongo
    void ReplSetImpl::relinquish(OperationContext* txn) {
        {
            Lock::GlobalWrite writeLock(txn->lockState());  // so we are synchronized with _logOp()

            LOG(2) << "replSet attempting to relinquish" << endl;
            if (box.getState().primary()) {
                log() << "replSet relinquishing primary state" << rsLog;
                changeState(MemberState::RS_SECONDARY);

                // close sockets that were talking to us so they don't blithly send many writes that
                // will fail with "not master" (of course client could check result code, but in
                // case they are not)
                log() << "replSet closing client sockets after relinquishing primary" << rsLog;
                MessagingPort::closeAllSockets(ScopedConn::keepOpen);
            }
            else if (box.getState().startup2()) {
                // This block probably isn't necessary
                changeState(MemberState::RS_RECOVERING);
                return;
            }
        }

        // now that all connections were closed, strip this mongod from all sharding details if and
        // when it gets promoted to a primary again, only then it should reload the sharding state
        // the rationale here is that this mongod won't bring stale state when it regains
        // primaryhood
        shardingState.resetShardingState();
    }
コード例 #19
0
ファイル: OBJ_usdcamera.cpp プロジェクト: lvxejay/USD
UsdGeomCamera
GusdOBJ_usdcamera::_LoadCamera(fpreal t, int thread)
{
    /* XXX: Disallow camera loading until the scene has finished loading.
       What happens otherwise is that some parm values are pulled on
       during loading, causing a _LoadCamera request. If this happens before
       the node's parm values have been loaded, then we'll end up loading
       the camera using defaults (which reference the shot conversion).
       So if we don't block this, we end up always loading the shot conversion,
       even if we don't need it! */

    if(_isLoading)
        return UsdGeomCamera();

    /* Always return a null camera while saving.
       This is to prevent load errors from prematurely interrupting saves,
       which can lead to corrupt files.*/
    if(GusdUTverify_ptr(OPgetDirector())->getIsDoingExplicitSave())
        return UsdGeomCamera();

    {
        UT_AutoReadLock readLock(_lock);
        if(!_camParmsMicroNode.requiresUpdate(t))
            return _cam;
    }

    UT_AutoWriteLock writeLock(_lock);

    /* Other thread may already have loaded the cam, so only update if needed.*/
    if(_camParmsMicroNode.updateIfNeeded(t, thread))
    {
        _errors.clearAndDestroyErrors();
        _cam = UsdGeomCamera();

        GusdPRM_Shared prmShared;
        UT_String usdPath, primPath;

        evalStringT(usdPath, prmShared->filePathName.getToken(), 0, t, thread);
        evalStringT(primPath, prmShared->primPathName.getToken(), 0, t, thread);

        GusdUT_ErrorManager errMgr(_errors);
        GusdUT_ErrorContext err(errMgr);

        GusdStageCacheReader cache;
        if(UsdPrim prim = cache.GetPrimWithVariants(
               usdPath, primPath, GusdStageOpts::LoadAll(), &err).first) {

            // Track changes to the stage (eg., reloads)
            DEP_MicroNode* stageMicroNode =
                cache.GetStageMicroNode(prim.GetStage());
            UT_ASSERT_P(stageMicroNode);
            _camParmsMicroNode.addExplicitInput(*stageMicroNode);

            _cam = GusdUSD_Utils::MakeSchemaObj<UsdGeomCamera>(prim, &err);
            return _cam;
        }
    }
    return UsdGeomCamera();
}
コード例 #20
0
void EntityEditFilters::removeFilter(EntityItemID entityID) {
    QWriteLocker writeLock(&_lock);
    FilterData filterData = _filterDataMap.value(entityID);
    if (filterData.valid()) {
        delete filterData.engine;
    }
    _filterDataMap.remove(entityID);
}
コード例 #21
0
ファイル: plugin_cache.cpp プロジェクト: wyrover/nscp
void nsclient::core::plugin_cache::add_plugin(nsclient::core::plugin_type plugin) {
	boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(5));
	if (!writeLock.owns_lock()) {
		LOG_ERROR_CORE("FATAL ERROR: Could not get write-mutex.");
		return;
	}
	plugin_cache_.push_back(plugin_cache_item(plugin));
}
コード例 #22
0
ファイル: ShTimer.cpp プロジェクト: ChadMcKinney/Shoggoth
void ShTimer::stop()
{
    boost::upgrade_lock<boost::shared_mutex> lock(timerMutex);
    boost::upgrade_to_unique_lock<boost::shared_mutex> writeLock(lock);
    running = false;
    //std::cout << "ShTimer FINISHED JOIN" << std::endl;
    //std::cout << "ShTimer stopped" << std::endl;
}
コード例 #23
0
ファイル: MUPD.cpp プロジェクト: erisproject/eris
void MUPD::intraApply() {
    auto lock = writeLock(con);

    for (auto &res: reservations) {
        res.buy();
    }

    reservations.clear();
}
コード例 #24
0
CCachedDirectory * CSVNStatusCache::GetDirectoryCacheEntry(const CTSVNPath& path)
{
    CCachedDirectory::ItDir itMap = m_directoryCache.find(path);
    if ((itMap != m_directoryCache.end())&&(itMap->second))
    {
        // We've found this directory in the cache
        return itMap->second;
    }
    else
    {
        // if the CCachedDirectory is NULL but the path is in our cache,
        // that means that path got invalidated and needs to be treated
        // as if it never was in our cache. So we remove the last remains
        // from the cache and start from scratch.
        CAutoWriteLock writeLock(m_guard);

        // Since above there's a small chance that before we can upgrade to
        // writer state some other thread gained writer state and changed
        // the data, we have to recreate the iterator here again.
        itMap = m_directoryCache.find(path);
        if (itMap!=m_directoryCache.end())
        {
            delete itMap->second;
            m_directoryCache.erase(itMap);
        }
        // We don't know anything about this directory yet - lets add it to our cache
        // but only if it exists!
        if (path.Exists() && m_shellCache.IsPathAllowed(path.GetWinPath()) && !g_SVNAdminDir.IsAdminDirPath(path.GetWinPath()))
        {
            // some notifications are for files which got removed/moved around.
            // In such cases, the CTSVNPath::IsDirectory() will return true (it assumes a directory if
            // the path doesn't exist). Which means we can get here with a path to a file
            // instead of a directory.
            // Since we're here most likely called from the crawler thread, the file could exist
            // again. If that's the case, just do nothing
            if (path.IsDirectory()||(!path.Exists()))
            {
                std::unique_ptr<CCachedDirectory> newcdir (new CCachedDirectory (path));
                if (newcdir.get())
                {
                    itMap = m_directoryCache.lower_bound (path);
                    ASSERT (   (itMap == m_directoryCache.end())
                            || (itMap->path != path));

                    itMap = m_directoryCache.insert
                        (itMap, std::make_pair (path, newcdir.release()));
                    if (!path.IsEmpty())
                        CSVNStatusCache::Instance().AddFolderForCrawling(path);

                    return itMap->second;
                }
                m_bClearMemory = true;
            }
        }
        return NULL;
    }
}
コード例 #25
0
ファイル: HashContainer.cpp プロジェクト: pantuspavel/hash
void HashContainer::removeOneValueFromValues(double val)
{
	// Need to eraze only one entrance of the value

	WriteLock writeLock(valuesLocker);

	ValuesSet::iterator it = values.find(val);
	values.erase(it);
}
コード例 #26
0
void VectorMatrix::randomize()
{
	const int dev = computeStrategy1();
	writeLock(dev);
	for (int c=0; c<num_arrays; ++c) {
		matty::getDevice(dev)->randomize(getArray(dev, c));
	}
	writeUnlock(dev);
}
コード例 #27
0
 void PublishingService::closePublisher(const std::string & name)
 {
     Lock writeLock(mPublishersMutex);
     Publishers::iterator iter = mPublishers.find(name);
     if (iter != mPublishers.end())
     {
         mPublishers.erase(iter);
     }
 }
コード例 #28
0
 bool upload(int texture_id, int width, int height) {
     if(!writeLock()) return false;
     metadata->timestamp = get_precise_time();
     glBindTexture(GL_TEXTURE_2D, texture_id);
     glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
     fprintf(stderr, "upload: %d %d", texture_id, (int)pixels[0]);
     writeUnlock();
     return true;
 }
コード例 #29
0
ファイル: plugin_cache.cpp プロジェクト: wyrover/nscp
void nsclient::core::plugin_cache::add_plugins(const plugin_cache_list_type & item) {
	boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(5));
	if (!writeLock.owns_lock()) {
		LOG_ERROR_CORE("FATAL ERROR: Could not get write-mutex.");
		return;
	}
	plugin_cache_.insert(plugin_cache_.end(), item.begin(), item.end());
	has_all_ = true;
}
コード例 #30
0
 bool StubFactoryRegistry::insertStubFactory(
     const std::string &objectName,
     const std::string &desc,
     StubFactoryPtr stubFactoryPtr)
 {
     RCF_UNUSED_VARIABLE(desc);
     WriteLock writeLock(mStubFactoryMapMutex);
     mStubFactoryMap[ objectName ] = stubFactoryPtr;
     return true;
 }