std::vector<unsigned char> GrammarReceiver::CreateStepOutRequest()
 {
     {
         std::unique_lock<std::mutex> uniqueLock(recognizerQueueMutex);
         recognizerQueue.push_back(std::shared_ptr<BaseRecognizer>(
                 new Recognizer<ReplyGrammar, Reply>(replyGrammar, 0)));
     }
     return {REQ, INT_SHIFT + 0x16, EOM};
 }
Exemple #2
0
    std::string HashTable::set(const CommandHandler::Arguments &arguments)
    {
        // get exclusive lock
        boost::upgrade_lock<boost::shared_mutex> lock(m_access);
        boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

        m_table[arguments[1] /* key */] = arguments[2] /* value */;

        return CommandHandler::REPLY_OK;
    }
    std::vector<unsigned char> GrammarReceiver::CreateGetLocalsRequest()
    {
        {
            std::unique_lock<std::mutex> uniqueLock(recognizerQueueMutex);

            recognizerQueue.push_back(std::shared_ptr<BaseRecognizer>(
                    new Recognizer<ReplyNameValueArrayGrammar, ReplyNameValueArray>(
                            replyNameValueArrayGrammar, replyNameValueArrayReceiver)));
        }
        return {REQ, INT_SHIFT + 0x1d, EOM};
    }
void MediaConvert::abort(){
	std::unique_lock<std::mutex> uniqueLock(mutex);
	if(!isEnded()){
		isAbort = true;
		convertState = ABORT;
		if(process != 0){
			process->terminateProcess();
		}
	}
	condition.notify_one();
}
void LimitDecrementerBody::Process(void)
{
    GarbageCollectorPtr->InputHasBeenProcessed(imageWrapperIn_, GarbageCollector::NOTIFY_IF_PROCESSED);

    GarbageCollector::GarbageItem* garbageItem = GarbageCollectorPtr->GetGarbageItem(imageWrapperIn_);
    while(garbageItem && !std::get<GarbageCollector::PRESENT>(*garbageItem)) 
    {
        std::unique_lock<tbb::mutex> uniqueLock(*std::get<GarbageCollector::MUTEX>(*garbageItem));
        std::get<GarbageCollector::COND_VAR>(*garbageItem)->wait(uniqueLock);
    }

    GarbageCollectorPtr->EraseEntry(imageWrapperIn_);
}
Exemple #6
0
    std::string HashTable::del(const CommandHandler::Arguments &arguments)
    {
        // get exclusive lock
        boost::upgrade_lock<boost::shared_mutex> lock(m_access);
        boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

        Table::const_iterator value = m_table.find(arguments[1]);
        if (value == m_table.end()) {
            return CommandHandler::REPLY_FALSE;
        }

        m_table.erase(value);
        return CommandHandler::REPLY_TRUE;
    }
Exemple #7
0
std::unique_ptr<EntryList> Spectrum2D::_get_spectrum(std::initializer_list<Pair> list) {
  int min0, min1, max0, max1;
  if (list.size() != 2) {
    min0 = min1 = 0;
    max0 = max1 = metadata_.resolution;
  } else {
    Pair range0 = *list.begin(), range1 = *(list.begin()+1);
    min0 = range0.first; max0 = range0.second;
    min1 = range1.first; max1 = range1.second;
  }

  std::unique_ptr<std::list<Entry>> result(new std::list<Entry>);
  CustomTimer makelist(true);

  if (buffered_ && !temp_spectrum_.empty()) {
    for (auto it : temp_spectrum_) {
      int co0 = it.first.first, co1 = it.first.second;
      if ((min0 <= co0) && (co0 < max0) && (min1 <= co1) && (co1 < max1)) {
        Entry newentry;
        newentry.first.resize(2, 0);
        newentry.first[0] = co0;
        newentry.first[1] = co1;
        newentry.second = it.second;
        result->push_back(newentry);
      }
    }
  } else {
    for (auto it : spectrum_) {
      int co0 = it.first.first, co1 = it.first.second;
      if ((min0 <= co0) && (co0 < max0) && (min1 <= co1) && (co1 < max1)) {
        Entry newentry;
        newentry.first.resize(2, 0);
        newentry.first[0] = co0;
        newentry.first[1] = co1;
        newentry.second = it.second;
        result->push_back(newentry);
      }
    }
  }
  if (!temp_spectrum_.empty()) {
    boost::unique_lock<boost::mutex> uniqueLock(u_mutex_, boost::defer_lock);
    while (!uniqueLock.try_lock())
      boost::this_thread::sleep_for(boost::chrono::seconds{1});
    temp_spectrum_.clear(); //assumption about client
  }
//  PL_DBG << "<Spectrum2D> Making list for " << metadata_.name << " took " << makelist.ms() << "ms filled with "
//         << result->size() << " elements";
  return result;
}
Exemple #8
0
duk_size_t DukDebugger::duk_trans_dvalue_read(void *udata, char *buffer, duk_size_t length)
{
    
    std::unique_lock<std::mutex> uniqueLock(outputBufferMutex);
    
    if (outputBuffer.size() > 0)
    {
        return innerSendData(buffer, length);
    }
    
    //Oops, we don't have anything, we need to wait
    
    outputBufferConditionVariable.wait(uniqueLock, [this]{ return this->outputBuffer.size() > 0; }); //Inner content of predicate function is protected by uniqueLock
    
    return innerSendData(buffer, length);
}
void BootstrapResampler::setupResample(int nResamples, SNPTable* snpt) {
    //make sure only one resampler is active at a time
    boost::mutex::scoped_lock uniqueLock(brMutex);

    BootstrapResampler::nResamples = nResamples;
    BootstrapResampler::maxResamples = nResamples;


    boost::thread_group tg;
    for (int i = 0; i < Parameters::nThreads; ++i) {
        tg.create_thread(boost::bind(&doResample, snpt, i));
        //tg.create_thread(boost::bind(&this->doResample, snpt,i));
    }
    tg.join_all();
    uniqueLock.unlock();
}
   bool 
   WhiteListCache::IsWhitelisted(const String &fromAddress, const IPAddress &address)
   {
      // Create a lock for shared operations
      boost::upgrade_lock< boost::shared_mutex > lock(_whitelistAccessMutex);

      if (_needRefresh)
      {
         // We need exclusive access to be able to upade the cache
         boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);

         Refresh();
      }

      vector<shared_ptr<WhiteListAddress> >::iterator iter = _whitelistItems.begin();
      vector<shared_ptr<WhiteListAddress> >::iterator iterEnd = _whitelistItems.end();

      for (; iter != iterEnd; iter++)
      {
         shared_ptr<WhiteListAddress> pWhiteAddress = (*iter);

         IPAddress iLowerIP = pWhiteAddress->GetLowerIPAddress();
         IPAddress iUpperIP = pWhiteAddress->GetUpperIPAddress();

         if (address.WithinRange(iLowerIP, iUpperIP))
         {
            String sWhiteEmailAddr = pWhiteAddress->GetEmailAddress();

            if (sWhiteEmailAddr.IsEmpty() || sWhiteEmailAddr == _T("*"))
            {
               // White listed
               return true;
            }

            // Check if the senders email address matches
            if (StringParser::WildcardMatchNoCase(sWhiteEmailAddr, fromAddress))
            {
               // White listed
               return true;
            }
         }
      }

      return false;

   }
Exemple #11
0
	uint8_t* importShareableMemoryBlock(const Fora::ShareableMemoryBlockHandle& inHandle)
		{
		if (inHandle.isEmpty())
			return nullptr;

		long shareableBlockIndex = ((size_t)inHandle.getBaseAddress()) % kSmallPrime;

		boost::upgrade_lock<boost::shared_mutex> lock(
			mShareableMemoryBlockMutexes[shareableBlockIndex]
			);

		boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

		mShareableMemoryBlocks[shareableBlockIndex].increfShareableMemoryBlockAndReturnIsNew(inHandle);

		return inHandle.getBaseAddress();
		}
Exemple #12
0
		inline result_type blockingDequeue(T & elem)
		{
			if (shouldQuit)
				return FAILURE;

			std::unique_lock<std::mutex> uniqueLock(queueAccessMutex);
			while (q.empty()) {
				queueAccessCondVar.wait(uniqueLock);
				if (shouldQuit) {
					uniqueLock.unlock();
					return FAILURE;
				}
			}
			internalDequeue(elem);
			uniqueLock.unlock();
			return SUCCESS;
		}
    std::vector<unsigned char> GrammarReceiver::CreateAddBreakpointRequest(std::string fileName, int line)
    {
        {
            std::unique_lock<std::mutex> uniqueLock(recognizerQueueMutex);
            recognizerQueue.push_back(std::shared_ptr<BaseRecognizer>(
                    new Recognizer<ReplyIntGrammar, ReplyInt>(replyIntGrammar, replyAddBreakpointReceiver)));
        }

        std::vector<unsigned char> result =  {REQ, INT_SHIFT + 0x18};

        if (fileName.size() <= 31)
        {
            result.push_back(0x60 + static_cast<unsigned char>(fileName.size()));
        }
        else
        {
            unsigned char hi = static_cast<unsigned char>(fileName.size() % 256);
            unsigned char lo = static_cast<unsigned char>(fileName.size() / 256);
            result.push_back(0x12);
            result.push_back(hi);
            result.push_back(lo);
        }

        for (int i = 0; i < fileName.size(); i++)
        {
            result.push_back(static_cast<unsigned char>(fileName[i]));
        }

        if (line <= 63)
        {
            result.push_back(0x80 + static_cast<unsigned char>(line));
        }
        else if (line >= 64 && line <= 16383)
        {
            unsigned char hi = static_cast<unsigned char>(line / 256);
            unsigned char lo = static_cast<unsigned char>(line % 256);
            result.push_back(0xc0 + hi);
            result.push_back(lo);
        }
        

        result.push_back(EOM);
        return result;
    }
Exemple #14
0
	/// <summary>
	/// Initializes underlying hardware.
	/// </summary>
	/// <returns>0 on success, non-zero for failures.</returns>
	int MaterialMonitor::InitHW(unsigned char *pucCartridgesCount)
	{
		UniqueLock uniqueLock(m_mtx);

		int returnValue = IDTLIB_SUCCESS;
		if (pucCartridgesCount == NULL)
		{
			returnValue = FCB_NULL_PARAM;
			LOG_EXT(LEVEL_FATAL, "Error initializing HW (error code 0x" << hex << (short)returnValue << ").");
			return returnValue;
		}

		m_bInitialized = false;
		returnValue = m_tagAdapter->InitHW(pucCartridgesCount);
		if (returnValue != IDTLIB_SUCCESS)
		{
			LOG_EXT(LEVEL_FATAL, "Error initializing HW (error code 0x" << hex << (short)returnValue << ").");
			return returnValue;
		}

		if (m_ucCartridgesCount != *pucCartridgesCount)
		{
			m_ucCartridgesCount = *pucCartridgesCount;
			if (m_certificates != NULL)
			{
				delete[] m_certificates;
			}

			m_certificates = new IDCertificate*[m_ucCartridgesCount];
		}

		for (unsigned char uc = 0; uc < m_ucCartridgesCount; uc++)
		{
			m_certificates[uc] = NULL;
		}

		LOG_EXT(LEVEL_INFO, "HW initialized successfully. Number of cartridges: " << (unsigned short)(*pucCartridgesCount) << ".");
		m_bInitialized = true;
		return returnValue;
	}
inline std::string AddEntry(const std::string& logSource, const std::unordered_set<std::string>& tags)
{
    std::string formattedTags = "";

    // Conglomerate all the tags.
    for (auto it = tags.begin(); it != tags.end(); ++it)
    {
        formattedTags += *it + ", ";
    }

    // Remove the trailing ", " if it exists.
    if (!formattedTags.empty())
    {
        formattedTags = formattedTags.substr(0, formattedTags.size() - 2);
    }

    // Obtain writer access 
    boost::upgrade_lock<boost::shared_mutex> lock(lineToStringMutex);
    boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
    lineToStringRep.emplace(logSource, formattedTags);
	return formattedTags;
}
Exemple #16
0
	virtual void free(uint8_t* inBytes) 
		{
		if (!Fora::ShareableMemoryBlock::isValidBaseAddress(inBytes))
			{
			::free(inBytes);
			return;
			}

		long shareableBlockIndex = ((size_t)inBytes) % kSmallPrime;

		boost::upgrade_lock<boost::shared_mutex> lock(
			mShareableMemoryBlockMutexes[shareableBlockIndex]
			);

		if (mShareableMemoryBlocks[shareableBlockIndex].hasShareableMemoryBlockHandle(inBytes))
			{
			boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

			mShareableMemoryBlocks[shareableBlockIndex].decrefSharedMemoryBlock(inBytes);
			}
		else
			::free(inBytes);
		}
void ObjectAccessor::RemoveCorpse(Corpse* corpse)
{
    ASSERT(corpse && corpse->GetType() != CORPSE_BONES);

    boost::upgrade_lock<boost::shared_mutex> lock(_corpseLock);

    /// @todo more works need to be done for corpse and other world object
    if (Map* map = corpse->FindMap())
    {
        corpse->DestroyForNearbyPlayers();
        if (corpse->IsInGrid())
            map->RemoveFromMap(corpse, false);
        else
        {
            corpse->RemoveFromWorld();
            corpse->ResetMap();
        }
    }
    else

        corpse->RemoveFromWorld();

    // Critical section
    {
        boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

        Player2CorpsesMapType::iterator iter = i_player2corpse.find(corpse->GetOwnerGUID());
        if (iter == i_player2corpse.end()) /// @todo Fix this
            return;

        // build mapid*cellid -> guid_set map
        CellCoord cellCoord = Trinity::ComputeCellCoord(corpse->GetPositionX(), corpse->GetPositionY());
        sObjectMgr->DeleteCorpseCellData(corpse->GetMapId(), cellCoord.GetId(), corpse->GetOwnerGUID().GetCounter());

        i_player2corpse.erase(iter);
    }
}
Exemple #18
0
void Dispatcher::thread() {
	std::unique_lock<std::mutex> uniqueLock(_mutex, std::defer_lock);

	while (_state == State::STARTED) {
		uniqueLock.lock();

		if (_tasks.empty()) {
			_signal.wait(uniqueLock);
		}

		if (_state != State::STARTED || _tasks.empty()) {
			uniqueLock.unlock();
			continue;
		}

		auto task = std::move(_tasks.front());
		_tasks.pop_front();

		uniqueLock.unlock();

		auto& game = server.game();
		auto messagePool = OutputMessagePool::getInstance();

		runTask(*task, game, messagePool);
	}

	_mutex.lock();
	auto tasks = std::move(_tasks);
	_mutex.unlock();

	runTasks(tasks);

	_mutex.lock();
	_state = State::STOPPED;
	_mutex.unlock();
}
void Logger::
log()
{
	std::unique_lock<std::mutex> uniqueLock(s_mutex);
	std::cout << "Num of elements: " << s_dataContainer.size() << "\n";
}
void MediaConvert::enableOverwriteFile(){
	std::unique_lock<std::mutex> uniqueLock(mutex);
	convertState = WAITING;
	enableOverwrite = true;
	condition.notify_one();
}
void MediaConvert::setOverwievState(){
	std::unique_lock<std::mutex> uniqueLock(mutex);
	convertState = OVERWRITE;
}
Exemple #22
0
 void Client::resetOperationContext() {
     invariant(_txn != NULL);
     boost::unique_lock<SpinLock> uniqueLock(_lock);
     _txn = NULL;
 }
Exemple #23
0
void Ipsum::operator()()
{
	std::cout << "Ipsum::operator()()" << std::endl;
    while(!(*stop))
    {
        std::unique_lock<std::mutex> uniqueLock(*ipsumConditionVariableMutex);
        ipsumConditionVariable->wait(uniqueLock, [this] {return (!ipsumSendQueue->empty() || (*stop));});

        std::cout << "ipsum condition variable notified" << std::endl;

        while(!ipsumSendQueue->empty())
        {
            localIpsumSendQueue->push(ipsumSendQueue->getPacket());
        }

        if (IpsumUnreachable)
        {
            try
            {
                http->ipsumInfo();
                IpsumUnreachable = false;
            }
            catch (HttpError)
            {
                IpsumUnreachable = true;
            }
        }

        if(!IpsumUnreachable)
        {
            Packet * ipsumPacket;
            while(!localIpsumSendQueue->empty())
            {
                ipsumPacket = localIpsumSendQueue->front();

                switch(ipsumPacket->getPacketType())
                {
                    case IPSUM_UPLOAD:
                        uploadDataHandler(dynamic_cast<IpsumUploadPacket *> (ipsumPacket));
                    break;
                    case IPSUM_CHANGE_IN_USE:
                        changeInUseHandler(dynamic_cast<IpsumChangeInUsePacket *> (ipsumPacket));
                    break;
                    case IPSUM_CHANGE_FREQ:
                        changeFrequencyHandler(dynamic_cast<IpsumChangeFreqPacket *> (ipsumPacket));
                    break;
                    default:
                    std::cerr << "packet type not recognized in ipsum thread" << std::endl;
                    // Packet not recognized

                }
            }
        }
        else if(*stop)
        {
            /*  Ipsum thread is going to exit but Ipsum has been unreachable. Data will be lost here
             *  Solution is to send the packets in the local queue back to main and main should store them in sql db somehow.
             *  Storing them in main could be done by using the boost serialization library http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/index.html.
             *  This might be too heavyweight so a system to store the relevant info in the sql db in main is a better solution
             */
            std::cerr << "Ipsum exited with cached packets in the local queue, these packets are now lost" << std::endl;
        }
        else
        {
            std::cerr << "Ipsum unreachable, packed stored in queue" << std::endl;
        }
    }
}
void MediaConvert::setNewName(const std::string& fileName){
	std::unique_lock<std::mutex> uniqueLock(mutex);
	convertState = WAITING;
	this->fileName = fileName;
	condition.notify_one();
}
void MediaConvert::convert(const bool enableFileThreading, const int numOfThreads, bool valid, double duration){
	if(valid){
		std::unique_lock<std::mutex> uniqueLock(mutex);
		while(this->getOutputFilePath().exist() && !enableOverwrite && !isAbort){
			convertState = OVERWRITE;
			condition.wait(uniqueLock);
		}
		if(isAbort){
			convertState = ABORT;
			return;
		}

		convertState = PROCESSING;

		generator.setThreading(enableFileThreading, numOfThreads);

		std::list<std::string> arguments = generator.generate();
		arguments.push_front("-y");
		arguments.push_front(mediaPath.getPath());
		arguments.push_front("-i");
		arguments.push_back(getOutputFilePath().getPath());
		auto extConverter = UserPreferences::getInstance()->getExtConverterPath();
		std::stringstream textCommand;
		textCommand<<"command:"<<std::endl;
		textCommand<<extConverter.getPath();
		for(auto x : arguments){
			textCommand<<" "<<x;
		}
		textCommand<<std::endl<<std::endl;
		errorOutputBuffer << textCommand.str();
		Converter::ConvertParser parser(duration);
		process = new ProcessExecutor::Process(extConverter.getPath(), arguments);
		process->waitForProcessBegin();
		uniqueLock.unlock();
		auto& stderr = process->getStdErr();
		std::string line;
		while(stderr >> line){
			double tmpFraction = 0;
			int tmpTime = 0;
			bool processOk = parser.processLine(line, tmpFraction, tmpTime);
			if(processOk){
				fraction = tmpFraction;
				if(tmpTime > 0){
					remainingTime = tmpTime;
				}
			}else{
				errorOutputBuffer << line << std::endl;
			}
		}
		int res = process->waitForProcessEnd();
		if(res != 0){
			convertState = FAIL;
		}else{
			convertState = FINISH;
		}
		fraction = 1;
		remainingTime = 0;
		uniqueLock.lock();
		delete process;
		process = NULL;
		uniqueLock.unlock();
	}else{
MediaConvert::ConvertState MediaConvert::getConvertState(){
	std::unique_lock<std::mutex> uniqueLock(mutex);
	return convertState;
}
Exemple #27
0
	void CGEFrameRecorder::runProc()
	{	
		//processingFilters 将可能改变 targetTextureID和bufferTextureID, lock 以保证其他线程使用
		std::unique_lock<std::mutex> uniqueLock(m_resultMutex);

		if(m_globalFilter != nullptr)
		{
			m_frameHandler->processingWithFilter(m_globalFilter);
		}

		m_frameHandler->processingFilters();

		if(isRecordingStarted() && !m_isRecordingPaused)
		{

			//第一帧必然记录
			if(m_recordingTimestamp == 0.0)
			{
				m_recordingTimestamp = 0.0001; //设置为 0.0001 ms, 表示已经开始
				m_lastRecordingTime = getCurrentTimeMillis();
				CGE_LOG_INFO("first frame...");
			}
			else
			{
				double currentTime = getCurrentTimeMillis();
				m_recordingTimestamp += currentTime - m_lastRecordingTime;
				m_lastRecordingTime = currentTime;
				// CGE_LOG_INFO("time stamp %g...", m_recordingTimestamp);
			}

			int ptsInFact = m_recordingTimestamp * (m_recordFPS / 1000.0);

			if(ptsInFact < m_currentPTS)
			{
				CGE_LOG_INFO("帧速过快, 丢弃帧...");
				return ;
			}
			else if(ptsInFact > m_currentPTS + 3)
			{
				CGE_LOG_INFO("帧速较慢, 填补帧...");
				m_currentPTS = ptsInFact;
			}
			else
			{
				// CGE_LOG_INFO("帧速合适的很...");
				if(m_currentPTS == ptsInFact)
					m_currentPTS = ptsInFact + 1;
				else
					m_currentPTS = ptsInFact;
			}

			if(m_recordThread != nullptr)
			{
				m_frameHandler->useImageFBO();
				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_frameHandler->getBufferTextureID(), 0);

				glViewport(0, 0, m_dstSize.width, m_dstSize.height);
				m_cacheDrawer->drawTexture(m_frameHandler->getTargetTextureID());
				glFinish();
				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_frameHandler->getTargetTextureID(), 0);

				if(m_recordThread->isActive() && m_recordThread->totalWorks() != 0)
					return;

				m_recordThread->run(CGEThreadPool::Work(m_recordingWork, (void*)m_currentPTS));
			}
			else
			{
				auto bufferCache = m_recordImageThread->getData4Write();

				if(bufferCache.buffer != nullptr)
				{
					// auto tm = getCurrentTimeMillis();

					m_frameHandler->useImageFBO();

					// CGE_LOG_ERROR("draw texture 时间: %g", (getCurrentTimeMillis() - tm));

					glReadPixels(0, 0, m_dstSize.width, m_dstSize.height, GL_RGBA, GL_UNSIGNED_BYTE, bufferCache.buffer);

					// CGE_LOG_ERROR("录制readpixel时间: %g", (getCurrentTimeMillis() - tm));
					bufferCache.pts = m_currentPTS;
					m_recordImageThread->putData4Read(bufferCache);
				}
			}
		}
	}
Exemple #28
0
duk_size_t DukDebugger::duk_trans_dvalue_peek(void *udata)
{
    std::unique_lock<std::mutex> uniqueLock(outputBufferMutex);

    return outputBuffer.size();
}
Exemple #29
0
	void TestManager::SetStop(bool value)
	{
		UniqueLock uniqueLock(m_mtx);
		m_bStop = value;
	}
Exemple #30
0
	bool TestManager::GetStop() const
	{
		UniqueLock uniqueLock(m_mtx);
		return m_bStop;
	}