Exemplo n.º 1
0
void TCPConnection::ClearBuffers() {
	LockMutex lock1(&MSendQueue);
	LockMutex lock3(&MRunLoop);
	LockMutex lock4(&MState);
	safe_delete_array(recvbuf);
	safe_delete_array(sendbuf);

	char* line = 0;
	while ((line = LineOutQueue.pop()))
		safe_delete_array(line);
}
Exemplo n.º 2
0
STDMETHODIMP TffdshowVideoInputPin::EndOfStream()
{
    CAutoLock lock1((CCritSec*)fv->deci->get_csReceive_ptr());
    CAutoLock lock2(&m_csCodecs_and_imgFilters);
    if (m_rateAndFlush.m_flushing) {
        return S_OK;
    }
    m_rateAndFlush.m_endflush = false;
    video->onEndOfStream();
    return TinputPin::EndOfStream();
}
SWDecoder const &SWDecoder::operator= (SWDecoder const &rhs)
{
	if(&rhs != this)
	{
		/* but here we need to lock both */
		boost::lock_guard<boost::mutex> lock1(&mMutex < &rhs.mMutex ? mMutex : rhs.mMutex);
		boost::lock_guard<boost::mutex> lock2(&mMutex > &rhs.mMutex ? mMutex : rhs.mMutex);
		mFinish = rhs.mFinish;
		mState  = rhs.mState;
	}
	return *this;
}
Exemplo n.º 4
0
void OperThreadWin::DBGPrintStoppingList()
{
	MutexLock lock1( &operMutex );

	OperThreadNode* p;

	for ( p = operStopList; p; p = p->next )
	{
		MutexLock lock2( &p->mutex );
		printf( "stopped thread %s\n", p->threadInfo.data() ? p->threadInfo.data() : "<empty info>" );
	}
}
Exemplo n.º 5
0
int main()
{
    boost::detail::lightweight_mutex::scoped_lock lock1( m1 );

    boost::detail::lightweight_mutex m2;
    boost::detail::lightweight_mutex m3;

    boost::detail::lightweight_mutex::scoped_lock lock2( m2 );
    boost::detail::lightweight_mutex::scoped_lock lock3( m3 );

    return 0;
}
Exemplo n.º 6
0
void bnf::CloseListen( session_handle handle )
{
	boost::recursive_mutex::scoped_lock lock1( tcp_listen_session_list_.getmutex() );

	map_session_list_t::iterator it = tcp_listen_session_list_.find(handle);
	if (it == tcp_listen_session_list_.end())
	{
		return;
	}

	delete it->second;
	tcp_listen_session_list_.erase(it);
}
Exemplo n.º 7
0
// Unmount a file system returning the number of open files were invalidated
unsigned int MassStorage::InternalUnmount(size_t card, bool doClose)
{
	SdCardInfo& inf = info[card];
	MutexLocker lock1(fsMutex);
	MutexLocker lock2(inf.volMutex);
	const unsigned int invalidated = InvalidateFiles(&inf.fileSystem, doClose);
	const char path[3] = { (char)('0' + card), ':', 0 };
	f_mount(nullptr, path, 0);
	memset(&inf.fileSystem, 0, sizeof(inf.fileSystem));
	sd_mmc_unmount(card);
	inf.isMounted = false;
	return invalidated;
}
Exemplo n.º 8
0
      /*! \brief Halt the threadpool and terminate all the threads.
       */
      inline void stop()
      {
	// _stop_flag must be set to true in a critical section.  Otherwise
	// it is possible for a thread to miss notify_all and never
	// terminate.
	{
	  std::unique_lock<std::mutex> lock1(_queue_mutex);
	  _stop_flag = true;       
	}
	
	_need_thread_mutex.notify_all();
	_threads.join_all();
      }
Exemplo n.º 9
0
/*ARGSUSED*/
int
maillock(char *user, int retrycnt)
{
	time_t t;
	struct stat sbuf;
	int statfailed;
	char locktmp[PATHSIZE];	/* Usable lock temporary */
	char file[PATHSIZE];

	if (locked)
		return (0);
	(void) strcpy(file, MAILDIR);
	(void) strcat(file, user);
	(void) strcpy(curlock, file);
	(void) strcat(curlock, lockext);
	(void) strcpy(locktmp, file);
	(void) strcat(locktmp, "XXXXXX");
	(void) mktemp(locktmp);
	(void) remove(locktmp);
	statfailed = 0;
	for (;;) {
		t = lock1(locktmp, curlock);
		if (t == (time_t)0) {
			locked = 1;
			locktime = time(0);
			return (0);
		}
		if (stat(curlock, &sbuf) < 0) {
			if (statfailed++ > 5)
				return (-1);
			(void) sleep(5);
			continue;
		}
		statfailed = 0;

		/*
		 * Compare the time of the temp file with the time
		 * of the lock file, rather than with the current
		 * time of day, since the files may reside on
		 * another machine whose time of day differs from
		 * ours.  If the lock file is less than 5 minutes
		 * old, keep trying.
		 */
		if (t < sbuf.st_ctime + 300) {
			(void) sleep(5);
			continue;
		}
		(void) remove(curlock);
	}
}
Exemplo n.º 10
0
/*==================================
	CreateBWCursor
===================================*/
Handle PTCursorView::CreateBWCursor( SUOffscreen *inImage, SUOffscreen *inMask, Point inHotSpot )
{
	CursHandle	h = (CursHandle) ::NewHandleClear( BWCursor_Bytes );
	ThrowIfMemFail_( h );
	StHandleLocker	lock1( (Handle) h );
	
	if ( inImage )
		inImage->CopyToRawData( (UInt8*) &(**h).data, BWCursor_RowBytes );
		
	if ( inMask )
		inMask->CopyToRawData( (UInt8*) &(**h).mask, BWCursor_RowBytes );
		
	(**h).hotSpot = inHotSpot;
	return( (Handle) h );
}
Exemplo n.º 11
0
Arquivo: main.cpp Projeto: CCJY/coliru
void transfer(bank_account &from, bank_account &to, int amount)
{
    // lock both mutexes without deadlock
    std::lock(from.m, to.m);
    // make sure both already-locked mutexes are unlocked at the end of scope
    std::lock_guard<std::mutex> lock1(from.m, std::adopt_lock);
    std::lock_guard<std::mutex> lock2(to.m, std::adopt_lock);
 
// equivalent approach:
//    std::lock_guard<std::mutex> lock1(from.m, std::defer_lock);
//    std::lock_guard<std::mutex> lock2(to.m, std::defer_lock);
//    std::lock(lock1, lock2);
 
    from.balance -= amount;
    to.balance += amount;
}
Exemplo n.º 12
0
bool
OpenLedger::modify (modify_type const& f)
{
    std::lock_guard<
        std::mutex> lock1(modify_mutex_);
    auto next = std::make_shared<
        OpenView>(*current_);
    auto const changed = f(*next, j_);
    if (changed)
    {
        std::lock_guard<
            std::mutex> lock2(
                current_mutex_);
        current_ = std::move(next);
    }
    return changed;
}
Exemplo n.º 13
0
void Renderer::Add(CRenderTarget* target, CRenderTarget* source1, CRenderTarget* source2)
{
	CRenderTargetLock lock(target);
	
	glDisable(GL_DEPTH_TEST);
	glDepthMask(GL_FALSE);

	COGLBindLock lockProgram(m_addProgram->GetGLProgram(), COGL_PROGRAM_SLOT);

	COGLBindLock lock0(source1->GetTarget(0), COGL_TEXTURE0_SLOT);
	COGLBindLock lock1(source2->GetTarget(0), COGL_TEXTURE1_SLOT);

	m_fullScreenQuad->draw();
	
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
}
Exemplo n.º 14
0
      /*! \brief Thread worker loop, called by the threads beginThreadFunc.
       */
      inline void beginThread()
      {
	try
	  {
	    std::unique_lock<std::mutex> lock1(_queue_mutex);
	    
	    while (!_stop_flag)
	      {
		if (_waitingFunctors.empty())
		  {
		    ++_idlingThreads;
		    //Let whoever is waiting know that the thread is now available
		    _threadAvailable_condition.notify_all();
		    //And send it to sleep
		    _need_thread_mutex.wait(lock1);
		    --_idlingThreads;
		    continue;
		  }
		
		std::function<void()> func = _waitingFunctors.front();
		_waitingFunctors.pop();
		
		lock1.unlock();
		
		try { func(); }
		catch(std::exception& cep)
		  {
		    //Mark the main process to throw an exception as soon as possible
		    std::lock_guard<std::mutex> lock2(_exception_mutex);
		    
		    _exception_data << "\nTHREAD: Task threw an exception:-"
				    << cep.what();
		    
		    _exception_flag = true;
		  }
		lock1.lock();
	      }
	  }
	catch (std::exception& p)
	  {
	    std::cout << "\nTHREAD :Catastrophic Failure of thread!!! System will Hang, Aborting!"
		      << p.what();
	    throw;
	  }
      }
Exemplo n.º 15
0
void RecLock()
{
    for(;;)
    {
        std::this_thread::sleep_for( std::chrono::milliseconds( 7 ) );
        std::lock_guard<LockableBase( std::recursive_mutex )> lock1( recmutex );
        TracyMessageL( "First lock" );
        LockMark( recmutex );
        ZoneScoped;
        {
            std::this_thread::sleep_for( std::chrono::milliseconds( 3 ) );
            std::lock_guard<LockableBase( std::recursive_mutex )> lock2( recmutex );
            TracyMessageL( "Second lock" );
            LockMark( recmutex );
            std::this_thread::sleep_for( std::chrono::milliseconds( 2 ) );
        }
    }
}
Exemplo n.º 16
0
STDMETHODIMP TffdshowVideoInputPin::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
    DPRINTF(_l("TffdshowVideoInputPin::NewSegment"));
    CAutoLock lock1((CCritSec*)fv->deci->get_csReceive_ptr());
    HRESULT hr = TinputPin::NewSegment(tStart, tStop, dRate);

    CAutoLock lock2(&m_csCodecs_and_imgFilters);
    if (hr == S_OK && codec) {
        codec->onSeek(tStart);
    }

    m_rateAndFlush.isDiscontinuity = true;
    m_rateAndFlush.rate.StartTime = m_rateAndFlush.ratechange.StartTime = 0;
    if (dRate != 0) {
        m_rateAndFlush.rate.Rate = m_rateAndFlush.ratechange.Rate = (LONG)(10000 / dRate);
    }
    return hr;
}
Exemplo n.º 17
0
Boolean VDBFlushMgr::SomethingToFlush(void)
{
	VTaskLock lock1(&ListFlushInfoMutext);
	BaseFlushInfo* curinfo;
	Boolean result = false;

	curinfo = ListFlushInfo;

	while (curinfo != nil)
	{
		VTaskLock lock2(&(curinfo->TreeMutex));
		if (curinfo->fCurTree != nil) result = true;
		curinfo = curinfo->right;
	}

	return result;

}
Exemplo n.º 18
0
 void MapPoint::SetBadFlag()
 {
     map<KeyFrame*,size_t> obs;
     {
         boost::mutex::scoped_lock lock1(mMutexFeatures);
         boost::mutex::scoped_lock lock2(mMutexPos);
         mbBad=true;
         obs = mObservations;
         mObservations.clear();
     }
     for(map<KeyFrame*,size_t>::iterator mit=obs.begin(), mend=obs.end(); mit!=mend; mit++)
     {
         KeyFrame* pKF = mit->first;
         pKF->EraseMapPointMatch(mit->second);
     }
     
     mpMap->EraseMapPoint(this);
 }
Exemplo n.º 19
0
void TranslationUnit::UpdateLatestDiagnostics() {
  unique_lock< mutex > lock1( clang_access_mutex_ );
  unique_lock< mutex > lock2( diagnostics_mutex_ );

  latest_diagnostics_.clear();
  size_t num_diagnostics = clang_getNumDiagnostics( clang_translation_unit_ );
  latest_diagnostics_.reserve( num_diagnostics );

  for ( size_t i = 0; i < num_diagnostics; ++i ) {
    Diagnostic diagnostic =
      BuildDiagnostic(
        DiagnosticWrap( clang_getDiagnostic( clang_translation_unit_, i ),
                        clang_disposeDiagnostic ),
        clang_translation_unit_ );

    if ( diagnostic.kind_ != INFORMATION )
      latest_diagnostics_.push_back( diagnostic );
  }
}
Exemplo n.º 20
0
void Renderer::CalculateError()
{
	CRenderTargetLock lock(m_errorRenderTarget.get());

	if(m_scene->GetReferenceImage())
	{
		glDisable(GL_DEPTH_TEST);
		glDepthMask(GL_FALSE);

		COGLBindLock lockProgram(m_errorProgram->GetGLProgram(), COGL_PROGRAM_SLOT);

		COGLBindLock lock0(m_resultRenderTarget->GetTarget(0), COGL_TEXTURE0_SLOT);
		COGLBindLock lock1(m_scene->GetReferenceImage()->GetOGLTexture(), COGL_TEXTURE1_SLOT);
		m_fullScreenQuad->draw();

		glEnable(GL_DEPTH_TEST);
		glDepthMask(GL_TRUE);
	}
}
Exemplo n.º 21
0
double LanguageModel::getKLD(
		LanguageModel *p, AbstractLanguageModel *q, AbstractLanguageModel *backgroundModel) {
	LocalLock lock1(p);
	LocalLock lock2(q);
	LocalLock lock3(backgroundModel);
	double result = 0.0;
	double coverage = 0.0;
	for (int i = 0; i < p->termSlotsUsed; i++) {
		char *term = p->terms[i].term;
		double bX = backgroundModel->getTermProbability(term);
		if (bX < 1E-10)
			continue;
		double pX = 0.8 * p->terms[i].termFrequency / p->corpusSize + 0.2 * bX;
		double qX = 0.8 * q->getTermProbability(term) + 0.2 * bX;
		coverage += pX;
		result += pX * log(pX / qX);
	}
	return result / coverage;
} // end of getKLD(LanguageModel*, AbstractLanguageModel*^2)
void FOOTPRINT_LIST_IMPL::StopWorkers()
{
    std::lock_guard<std::mutex> lock1( m_join );

    // To safely stop our workers, we set the cancellation flag (they will each
    // exit on their next safe loop location when this is set).  Then we need to wait
    // for all threads to finish as closing the implementation will free the queues
    // that the threads write to.
    for( auto& i : m_threads )
        i.join();

    m_threads.clear();
    m_queue_in.clear();
    m_count_finished.store( 0 );

    // If we have cancelled in the middle of a load, clear our timestamp to re-load next time
    if( m_cancelled )
        m_list_timestamp = 0;
}
Exemplo n.º 23
0
void
ThreadPool::Data::finish ()
{
    stop();

    //
    // Signal enough times to allow all threads to stop.
    //
    // Wait until all threads have started their run functions.
    // If we do not wait before we destroy the threads then it's
    // possible that the threads have not yet called their run
    // functions.
    // If this happens then the run function will be called off
    // of an invalid object and we will crash, most likely with
    // an error like: "pure virtual method called"
    //

    for (size_t i = 0; i < numThreads; i++)
    {
	taskSemaphore.post();
	threadSemaphore.wait();
    }

    //
    // Join all the threads
    //

    for (list<WorkerThread*>::iterator i = threads.begin();
	 i != threads.end();
	 ++i)
    {
	delete (*i);
    }

    Lock lock1 (taskMutex);
    Lock lock2 (stopMutex);
    threads.clear();
    tasks.clear();
    numThreads = 0;
    numTasks = 0;
    stopping = false;
}
Exemplo n.º 24
0
 void MapPoint::UpdateNormalAndDepth()
 {
     map<KeyFrame*,size_t> observations;
     KeyFrame* pRefKF;
     cv::Mat Pos;
     {
         boost::mutex::scoped_lock lock1(mMutexFeatures);
         boost::mutex::scoped_lock lock2(mMutexPos);
         if(mbBad)
             return;
         observations=mObservations;
         pRefKF=mpRefKF;
         Pos = mWorldPos.clone();
     }
     
     cv::Mat normal = cv::Mat::zeros(3,1,CV_32F);
     int n=0;
     for(map<KeyFrame*,size_t>::iterator mit=observations.begin(), mend=observations.end(); mit!=mend; mit++)
     {
         KeyFrame* pKF = mit->first;
         cv::Mat Owi = pKF->GetCameraCenter();
         cv::Mat normali = mWorldPos - Owi;
         normal = normal + normali/cv::norm(normali);
         n++;
     } 
     
     cv::Mat PC = Pos - pRefKF->GetCameraCenter();
     const float dist = cv::norm(PC);
     const int level = pRefKF->GetKeyPointScaleLevel(observations[pRefKF]);
     const float scaleFactor = pRefKF->GetScaleFactor();
     const float levelScaleFactor =  pRefKF->GetScaleFactor(level);
     const int nLevels = pRefKF->GetScaleLevels();
     
     {
         boost::mutex::scoped_lock lock3(mMutexPos);
         mfMinDistance = (1.0f/scaleFactor)*dist / levelScaleFactor;
         mfMaxDistance = scaleFactor*dist * pRefKF->GetScaleFactor(nLevels-1-level);
         mNormalVector = normal/n;
     }
 }
Exemplo n.º 25
0
void CResManage::ClearAllResource()
{
	map<HWND, list<VideoRender*> > mapRander;
	CSingleZenoLock lock1(m_mtxRander);
	mapRander.swap(m_mapRander);
	lock1.release();
	for (map<HWND, list<VideoRender*> >::iterator iter = mapRander.begin();iter != mapRander.end();++iter)
	{
		list<VideoRender*>& listRander = iter->second;
		for (list<VideoRender*>::iterator iter1 = listRander.begin();iter1 != listRander.end();++iter1)
		{
			delete *iter1;
		}
	}

	list<int> listPort[StreamSourceType_Num];
	CSingleZenoLock lock2(m_mtxPort);
	for (int i = 0;i < StreamSourceType_Num;i++)
	{
		listPort[i].swap(m_listPort[i]);
	}
	lock2.release();
	for (int i = 0;i < StreamSourceType_Num;i++)
	{
		for (list<int>::iterator iter = listPort[i].begin();iter != listPort[i].end();++iter)
		{
			PlaySDK_CloseStream(i, *iter);
			CNBPlayer::UnusePort(i, *iter);
		}
	}

	list<char*> listBuf;
	CSingleZenoLock lock3(m_mtxFrameBuffer);
	listBuf.swap(m_listFrameBuffer);
	lock3.release();
	for (list<char*>::iterator iter = listBuf.begin();iter != listBuf.end();++iter)
	{
		delete *iter;
	}
}
Exemplo n.º 26
0
bool ClientUnix::SendLine(const std::string *str, const struct timespec *Timeout)
{
	ScopedLock lock1(&m_WriterMutex);
	if (IsConnected() == false)
		return false;

	ScopedReadLock rlock(&m_WriterLock);

	const char *c = str->c_str();
	ssize_t offset = 0;
	ssize_t length = str->size();
	ssize_t ret = 0;
	
restart:
	ret = send(m_fd, &c[offset], length, MSG_NOSIGNAL);
	if (ret < 0)
	{
		switch(errno)
		{
			case EINTR:
				goto restart;
				break;
			default:
				RaiseOnSendError(errno, Errno::ToStr());
				return false;
		}
	}

	if (ret < length - offset)
	{
		length -= ret;
		offset += ret;
		goto restart;
	}

	//Success!
	return true;
}
Exemplo n.º 27
0
int TPTCPClient::Close()
{
	CReadWriteMutexLock lock(m_csOnline);
	m_bOnline = FALSE;
	m_bReconnEn = FALSE;
	lock.Unlock();

	ClearClientEnvironment();

	CReadWriteMutexLock lock1(m_csSendQueue);
	while (!m_lstSendQueue.empty())
	{
		DataRow *conn = m_lstSendQueue.front();
		if (conn != NULL)
		{
			delete conn;
		}
		m_lstSendQueue.pop();
	}
	lock1.Unlock();

	return 1;
}
Exemplo n.º 28
0
// merge other into this.  All options in other take precedence over this.
void robot_interaction::KinematicOptionsMap::merge(
      const KinematicOptionsMap& other)
{
  if (&other == this)
    return;

  // need to lock in consistent order to avoid deadlock.
  // Lock the one with lower address first.
  boost::mutex *m1 = &lock_;
  boost::mutex *m2 = &other.lock_;
  if (m2 < m1)
    std::swap(m1, m2);
  boost::mutex::scoped_lock lock1(*m1);
  boost::mutex::scoped_lock lock2(*m2);

  defaults_ = other.defaults_;
  for (M_options::const_iterator it = other.options_.begin() ;
       it != other.options_.end() ;
       ++it)
  {
    options_[it->first] = it->second;
  }
}
Exemplo n.º 29
0
  void Transfer(const ID from, const ID to, float amount) {
    IAccount *fromAccount, *toAccount;
    fromAccount = toAccount = nullptr;

    if (m_vecAccount.size() < from || m_vecAccount.size() < to)
      // account don't exist
      return;
      
    fromAccount = &m_vecAccount.at(from);
    toAccount = &m_vecAccount.at(to);

    // TODO: wrap into trans
    // don't actually take the locks yet
    std::unique_lock<std::mutex> lock1(fromAccount->Lock(), std::defer_lock);
    std::unique_lock<std::mutex> lock2(toAccount->Lock(), std::defer_lock);

    // lock both unique_locks without deadlock
    std::lock(lock1, lock2);

    fromAccount->Withdraw(amount);
    toAccount->Deposit(amount);

    toAccount = fromAccount = nullptr;
  }
Exemplo n.º 30
0
TEST(DragImageTest, InterpolationNone) {
  SkBitmap expectedBitmap;
  expectedBitmap.allocN32Pixels(4, 4);
  {
    SkAutoLockPixels lock(expectedBitmap);
    expectedBitmap.eraseArea(SkIRect::MakeXYWH(0, 0, 2, 2), 0xFFFFFFFF);
    expectedBitmap.eraseArea(SkIRect::MakeXYWH(0, 2, 2, 2), 0xFF000000);
    expectedBitmap.eraseArea(SkIRect::MakeXYWH(2, 0, 2, 2), 0xFF000000);
    expectedBitmap.eraseArea(SkIRect::MakeXYWH(2, 2, 2, 2), 0xFFFFFFFF);
  }

  SkBitmap testBitmap;
  testBitmap.allocN32Pixels(2, 2);
  {
    SkAutoLockPixels lock(testBitmap);
    testBitmap.eraseArea(SkIRect::MakeXYWH(0, 0, 1, 1), 0xFFFFFFFF);
    testBitmap.eraseArea(SkIRect::MakeXYWH(0, 1, 1, 1), 0xFF000000);
    testBitmap.eraseArea(SkIRect::MakeXYWH(1, 0, 1, 1), 0xFF000000);
    testBitmap.eraseArea(SkIRect::MakeXYWH(1, 1, 1, 1), 0xFFFFFFFF);
  }

  RefPtr<TestImage> testImage =
      TestImage::create(SkImage::MakeFromBitmap(testBitmap));
  std::unique_ptr<DragImage> dragImage = DragImage::create(
      testImage.get(), DoNotRespectImageOrientation, 1, InterpolationNone);
  ASSERT_TRUE(dragImage);
  dragImage->scale(2, 2);
  const SkBitmap& dragBitmap = dragImage->bitmap();
  {
    SkAutoLockPixels lock1(dragBitmap);
    SkAutoLockPixels lock2(expectedBitmap);
    for (int x = 0; x < dragBitmap.width(); ++x)
      for (int y = 0; y < dragBitmap.height(); ++y)
        EXPECT_EQ(expectedBitmap.getColor(x, y), dragBitmap.getColor(x, y));
  }
}