Example #1
0
wxThread::ExitCode MyThread::Entry() {

    while (Check()) {
        {
            wxCriticalSectionLocker locker(wxGetApp().myapp_critsect);

            // If stop button pressed then return immediately
            if ( wxGetApp().myapp_shut_down ) {
                return NULL;
            }
        }
        // check if just this thread was asked to exit
        if ( TestDestroy() )
            break;

        wxString login = Read();

        //mt_curl->SetLogin(login.BeforeFirst('@'));
        mt_curl->SetLogin(login);

        if (mt_curl->IsAvailable()) {
            wxCriticalSectionLocker lock(mt_critsect);
            num_good++;
            file_good.AddLine(login);
            file_good.Write();
            notif_str += login;
            notif_str += '\n';
        }
        else {
            wxCriticalSectionLocker lock(mt_critsect);
            num_bad++;
        }
    }
    return NULL;
}
Example #2
0
bool 
TTracker::CloseParentWaitingForChild(const entry_ref *child,
	const node_ref *parent)
{
	AutoLock<WindowList> lock(&fWindowList);
	
	BContainerWindow *parentWindow = FindContainerWindow(parent);
	if (!parentWindow)
		// parent window already closed, give up
		return true;

	// If child is a symbolic link, dereference it, so that
	// FindContainerWindow will succeed.
	BEntry entry(child, true);
	entry_ref resolvedChild;
	if (entry.GetRef(&resolvedChild) != B_OK)
		resolvedChild = *child;

	BContainerWindow *window = FindContainerWindow(&resolvedChild);
	if (window) {
		AutoLock<BWindow> lock(window);
		if (!window->IsHidden())
			return CloseParentWindowCommon(parentWindow);
	}
	return false;	
}
void
RememberCertErrorsTable::RememberCertHasError(TransportSecurityInfo* infoObject,
        nsSSLStatus* status,
        SECStatus certVerificationResult)
{
    nsresult rv;

    nsAutoCString hostPortKey;
    rv = GetHostPortKey(infoObject, hostPortKey);
    if (NS_FAILED(rv))
        return;

    if (certVerificationResult != SECSuccess) {
        NS_ASSERTION(status,
                     "Must have nsSSLStatus object when remembering flags");

        if (!status)
            return;

        CertStateBits bits;
        bits.mIsDomainMismatch = status->mIsDomainMismatch;
        bits.mIsNotValidAtThisTime = status->mIsNotValidAtThisTime;
        bits.mIsUntrusted = status->mIsUntrusted;

        MutexAutoLock lock(mMutex);
        mErrorHosts.Put(hostPortKey, bits);
    }
    else {
        MutexAutoLock lock(mMutex);
        mErrorHosts.Remove(hostPortKey);
    }
}
void vector_to_streams_ss_4o_base::stop() throw (CORBA::SystemException, CF::Resource::StopError)
{
    if ( short_in ) short_in->block();
    {
        boost::mutex::scoped_lock lock(_sriMutex);
        _sriQueue.clear();
    }

    // release the child thread (if it exists)
    if (serviceThread != 0) {
        {
            boost::mutex::scoped_lock lock(serviceThreadLock);
            LOG_TRACE( vector_to_streams_ss_4o_base, "Stopping Service Function" );
            serviceThread->stop();
        }

        if ( !serviceThread->release()) {
            throw CF::Resource::StopError(CF::CF_NOTSET, "Processing thread did not die");
        }

        boost::mutex::scoped_lock lock(serviceThreadLock);
        if ( serviceThread ) {
            delete serviceThread;
        }
    }
    serviceThread = 0;

    if (Resource_impl::started()) {
        Resource_impl::stop();
    }

    LOG_TRACE( vector_to_streams_ss_4o_base, "COMPLETED STOP REQUEST" );
}
Example #5
0
void CAmiko::stop()
{
	m_ListenerThread.stop();
	m_MakerThread.stop();
	m_FinRoutingThread.stop();

	{
		CMutexLocker lock(m_PendingComLinks);
		for(std::list<CComLink *>::iterator i=m_PendingComLinks.m_Value.begin();
			i != m_PendingComLinks.m_Value.end(); i++)
		{
			(*i)->setReceiver(NULL);
			(*i)->stop();
			delete (*i);
		}
		m_PendingComLinks.m_Value.clear();
	}

	{
		CMutexLocker lock(m_OperationalComLinks);
		for(std::list<CComLink *>::iterator i=m_OperationalComLinks.m_Value.begin();
			i != m_OperationalComLinks.m_Value.end(); i++)
		{
			(*i)->setReceiver(NULL);
			(*i)->stop();
			delete (*i);
		}
		m_OperationalComLinks.m_Value.clear();
	}
}
Example #6
0
int main() {
	std::mutex m;
	std::condition_variable cond_var;
    std::thread thread1([&m, &cond_var](){
        for(;;) {
        	std::this_thread::sleep_for(std::chrono::seconds(1));
        	std::unique_lock<std::mutex> lock(m);
        	std::cout << "first" << std::endl;
        	cond_var.notify_one();
        }
    });

    std::thread thread2([&m, &cond_var](){
        for(;;) {
        	std::unique_lock<std::mutex> lock(m);
        	cond_var.wait(lock);
        	std::cout << "second" << std::endl;
        }
    });

    thread1.join();
    thread2.join();

    return 0;
}
Example #7
0
BOOL CHPThreadPool::DoAdjustThreadCount(DWORD dwNewThreadCount)
{
	ASSERT((int)dwNewThreadCount >= 0);

	BOOL bRemove		= FALSE;
	DWORD dwThreadCount	= 0;

	{
		CCriSecLock lock(m_cs);

		if(dwNewThreadCount > m_dwThreadCount)
		{
			dwThreadCount = dwNewThreadCount - m_dwThreadCount;
			return CreateWorkerThreads(dwThreadCount);
		}
		else if(dwNewThreadCount < m_dwThreadCount)
		{
			bRemove			 = TRUE;
			dwThreadCount	 = m_dwThreadCount - dwNewThreadCount;
			m_dwThreadCount -= dwThreadCount;
		}
	}

	if(bRemove)
	{
		CMutexLock2 lock(m_mtx);

		for(DWORD i = 0; i < dwThreadCount; i++)
			m_cv.notify_one();
	}

	return TRUE;
}
Example #8
0
File: page.c Project: aahud/harvey
Page *
lookpage(Image *i, uint32_t daddr)
{
	Page *f;

	lock(&pga.hashlock);
	for(f = pghash(daddr); f; f = f->hash){
		if(f->image == i && f->daddr == daddr){
			unlock(&pga.hashlock);

			lock(&pga.l);
			lock(&f->l);
			if(f->image != i || f->daddr != daddr){
				unlock(&f->l);
				unlock(&pga.l);
				return 0;
			}
			if(++f->ref == 1)
				pageunchain(f);
			unlock(&pga.l);
			unlock(&f->l);

			return f;
		}
	}
	unlock(&pga.hashlock);

	return nil;
}
bool CombiningOutputComponent::requestOutput(const std::string& device,
		SurgSim::DataStructures::DataGroup* outputData)
{
	std::vector<std::shared_ptr<OutputComponent>> shareds;
	{
		boost::lock_guard<boost::mutex> lock(m_mutex);
		std::vector<std::vector<std::weak_ptr<OutputComponent>>::const_iterator> stale;
		for (auto weak = m_outputs.cbegin(); weak != m_outputs.cend(); ++weak)
		{
			auto shared = weak->lock();
			if (shared == nullptr)
			{
				stale.push_back(weak);
			}
			else
			{
				shareds.push_back(shared);
			}
		}

		std::reverse(stale.begin(), stale.end());
		for (auto it : stale)
		{
			m_outputs.erase(it);
		}
	}
	return m_combiner(shareds, outputData);
}
Example #10
0
	void RealSenseDetector::run() {
		while (!stopped){

			ImageGrayscale img;
			{
				Poco::Mutex::ScopedLock lock(imMutex);
				if (imageVector.size()) {
					img = imageVector.back();
					imageVector.clear();
				}
			}

			if (img.data == 0) {
				wakeEvent.wait();
				continue;
			}

			std::vector<cv::Rect> _rects = detectImpl(img);
			{
				Poco::Mutex::ScopedLock lock(rectMutex);
				this->rects = _rects;
			}
		}

	}
Example #11
0
File: page.c Project: aahud/harvey
/*
 * Get an auxiliary page.
 * Don't do so if less than Nminfree pages.
 * Only used by cache.
 * The interface must specify page size.
 */
Page*
auxpage(usize size)
{
	Page *p;
	Pgsza *pa;
	int si;

	si = getpgszi(size);
	lock(&pga.l);
	pa = &pga.pgsza[si];
	p = pa->head;
	if(pa->freecount < Nminfree){
		unlock(&pga.l);
		return nil;
	}
	pageunchain(p);
	lock(&p->l);
	if(p->ref != 0)
		panic("auxpage");
	p->ref++;
	uncachepage(p);
	unlock(&p->l);
	unlock(&pga.l);

	return p;
}
bool CZeroconfBrowserAndroid::doRemoveServiceType(const std::string& fcr_service_type)
{
  CLog::Log(LOGDEBUG, "CZeroconfBrowserAndroid::doRemoveServiceType: %s", fcr_service_type.c_str());

  CZeroconfBrowserAndroidDiscover* discover;
  //search for this browser and remove it from the map
  {
    CSingleLock lock(m_data_guard);
    tBrowserMap::iterator it = m_service_browsers.find(fcr_service_type);
    if(it == m_service_browsers.end())
    {
      return false;
    }
    discover = it->second;
    if (discover->IsActive())
      m_manager.stopServiceDiscovery(*discover);
    // Be extra careful: Discover listener is gone as of now
    m_service_browsers.erase(it);
  }

  //remove the services of this browser
  {
    CSingleLock lock(m_data_guard);
    tDiscoveredServicesMap::iterator it = m_discovered_services.find(discover);
    if(it != m_discovered_services.end())
      m_discovered_services.erase(it);
  }
  delete discover;

  return true;
}
Example #13
0
// Stop any unfinished business on the conduit; block until 
// everything is done and the object can be safely destroyed.
void SimpleConduit::finalize(){ 
    
    shared_ptr<Clock> clock = Clock::instance(false);
    
    {   // tell the system to stop
        boost::mutex::scoped_lock lock(stopping_mutex);
        stopping = true;
    }   // release the lock
    
    int n_wait_attempts = 5;
    int wait_count = 0;
    while(wait_count < n_wait_attempts){  // wait for the all clear that the conduit has finished
        
        wait_count++;
        
        bool _stopped = false;
        {
            boost::mutex::scoped_lock lock(stopping_mutex);
            _stopped = stopped;
        }
        
        if(_stopped){
            break;
        }
        
        clock->sleepMS(100);
    }
    
    
    if(wait_count >= n_wait_attempts){
        std::cerr << "Simple conduit finalization timed out" << std::endl;
    }
    
}
Example #14
0
static void 
timerproc ( void ) 
{ 
int64 delta , now; 
Timer *t; 
void ( *f ) ( int64 , Eface ) ; 
Eface arg; 
#line 198 "/home/14/ren/source/golang/go/src/pkg/runtime/time.goc"
for ( ;; ) { 
runtime·lock ( &timers ) ; 
timers.sleeping = false; 
now = runtime·nanotime ( ) ; 
for ( ;; ) { 
if ( timers.len == 0 ) { 
delta = -1; 
break; 
} 
t = timers.t[0]; 
delta = t->when - now; 
if ( delta > 0 ) 
break; 
if ( t->period > 0 ) { 
#line 213 "/home/14/ren/source/golang/go/src/pkg/runtime/time.goc"
t->when += t->period * ( 1 + -delta/t->period ) ; 
siftdown ( 0 ) ; 
} else { 
#line 217 "/home/14/ren/source/golang/go/src/pkg/runtime/time.goc"
timers.t[0] = timers.t[--timers.len]; 
timers.t[0]->i = 0; 
siftdown ( 0 ) ; 
t->i = -1; 
} 
f = ( void* ) t->fv->fn; 
arg = t->arg; 
runtime·unlock ( &timers ) ; 
if ( raceenabled ) 
runtime·raceacquire ( t ) ; 
f ( now , arg ) ; 
#line 230 "/home/14/ren/source/golang/go/src/pkg/runtime/time.goc"
f = nil; 
USED ( f ) ; 
arg.type = nil; 
arg.data = nil; 
USED ( &arg ) ; 
#line 236 "/home/14/ren/source/golang/go/src/pkg/runtime/time.goc"
runtime·lock ( &timers ) ; 
} 
if ( delta < 0 ) { 
#line 240 "/home/14/ren/source/golang/go/src/pkg/runtime/time.goc"
timers.rescheduling = true; 
runtime·parkunlock ( &timers , "timer goroutine (idle)" ) ; 
continue; 
} 
#line 245 "/home/14/ren/source/golang/go/src/pkg/runtime/time.goc"
timers.sleeping = true; 
runtime·noteclear ( &timers.waitnote ) ; 
runtime·unlock ( &timers ) ; 
runtime·notetsleepg ( &timers.waitnote , delta ) ; 
} 
} 
Example #15
0
void botClient::threadedFunction()
{
    std::wstring_convert <std::codecvt_utf8 <wchar_t>> cv;
    while (isThreadRunning())
    {
        if (!client.isConnected()) {
            ofLog(OF_LOG_NOTICE, "Connection to %s:%d", ip.c_str(), port);
            client.setup(ip, port);
            client.setMessageDelimiter("\r\n");
        }
        if (client.isConnected()) {
            if (!out_mess.empty()) {
                lock();
                client.send(out_mess.front());
                out_mess.pop();
                unlock();
            }

            client.send("ping\r\n");

            std::string mes = client.receive();
            if (mes.size()) {
                std::wstring s = cv.from_bytes(mes);
                ofLog(OF_LOG_NOTICE, "Recived message: %s", s.c_str());
                lock();
                in_mess.push(s);
                unlock();
            }
        }
        else {
            ofLog(OF_LOG_NOTICE, "Connection to %s:%d failed", ip.c_str(), port);
        }
        sleep(2000);
    } 
}
Example #16
0
    void Engine::Entity::setProperty(const EditableProperty& prop)
    {
       
        switch (prop.getType())
        {
            case EditableProperty::POSITION:
            {
                CORE_ASSERT(prop.getName() == "Position", "Wrong property");
                std::lock_guard<std::mutex> lock(m_transformMutex);
                m_transform.translation() = prop.asPosition();
                break;
            }
            case EditableProperty::ROTATION:
            {
                CORE_ASSERT(prop.getName() == "Rotation", "Wrong property");
                std::lock_guard<std::mutex> lock(m_transformMutex);
                m_transform.linear() = prop.asRotation().toRotationMatrix();
                break;
            }
            default:
                CORE_ASSERT(false, "Wrong property");

        }

    }
Example #17
0
void loadSceneAsync(const char* _scenePath, bool _useScenePosition, MapReady _platformCallback) {
    LOG("Loading scene file (async): %s", _scenePath);

    {
        std::lock_guard<std::mutex> lock(m_sceneMutex);
        m_sceneUpdates.clear();
        m_nextScene = std::make_shared<Scene>(_scenePath);
        m_nextScene->useScenePosition = _useScenePosition;
    }

    Tangram::runAsyncTask([scene = m_nextScene, _platformCallback](){

            bool ok = SceneLoader::loadScene(scene);

            Tangram::runOnMainLoop([scene, ok, _platformCallback]() {
                    {
                        std::lock_guard<std::mutex> lock(m_sceneMutex);
                        if (scene == m_nextScene) {
                            m_nextScene.reset();
                        } else { return; }
                    }

                    if (ok) {
                        auto s = scene;
                        Tangram::setScene(s);
                        Tangram::applySceneUpdates();
                        if (_platformCallback) { _platformCallback(); }
                    }
                });
        });
}
Example #18
0
void GeneralAttributeCheck::mapElements()
{
    if (!sGeneralAttCheckMutexRegistered)
    {
        if (!sGeneralAttCheckMutex)
        {
            XMLMutexLock lock(XMLPlatformUtils::fgAtomicMutex);

            if (!sGeneralAttCheckMutex)
                sGeneralAttCheckMutex = new XMLMutex(XMLPlatformUtils::fgMemoryManager);
        }

        // Use a faux scope to synchronize while we do this
        {
            XMLMutexLock lock(sGeneralAttCheckMutex);

            // If we got here first, then register it and set the registered flag
            if (!sGeneralAttCheckMutexRegistered)
            {
                // initialize
                setUpValidators();
                mapAttributes();

                // register for cleanup at Termination.
                sGeneralAttCheckCleanup.registerCleanup(GeneralAttributeCheck::reinitGeneralAttCheck);
                sGeneralAttCheckMutexRegistered = true;
            }
        }
    }
}
    void operator()()
    {
        mutex_type mutex;
        boost::condition condition;

        // Test the lock's constructors.
        {
            lock_type lock(mutex, false);
            BOOST_CHECK(!lock);
        }
        lock_type lock(mutex);
        BOOST_CHECK(lock ? true : false);

        // Construct and initialize an xtime for a fast time out.
        boost::xtime xt = delay(0, 100);

        // Test the lock and the mutex with condition variables.
        // No one is going to notify this condition variable.  We expect to
        // time out.
        BOOST_CHECK(!condition.timed_wait(lock, xt));
        BOOST_CHECK(lock ? true : false);

        // Test the lock and unlock methods.
        lock.unlock();
        BOOST_CHECK(!lock);
        lock.lock();
        BOOST_CHECK(lock ? true : false);
    }
Example #20
0
EXPORT_C GSgetTitleInfo2(char* dest, size_t length)
{
	if (gsopen_done == false) {
		//printf("GSdx: GSgetTitleInfo but GSOpen not yet done. Ignoring\n");
		return;
	}

	string s = "GSdx";

	// TODO: this gets called from a different thread concurrently with GSOpen (on linux)
	if(s_gs == NULL) return;

	if(s_gs->m_GStitleInfoBuffer[0])
	{
#ifdef _CX11_
		std::lock_guard<std::mutex> lock(s_gs->m_pGSsetTitle_Crit);
#else
		GSAutoLock lock(&s_gs->m_pGSsetTitle_Crit);
#endif

		s = format("GSdx | %s", s_gs->m_GStitleInfoBuffer);

		if(s.size() > length - 1)
		{
			s = s.substr(0, length - 1);
		}
	}

	strcpy(dest, s.c_str());
}
void BULKIO_dataFloat_In_i::pushSRI(const BULKIO::StreamSRI& H)
{
    boost::mutex::scoped_lock lock(sriUpdateLock);
    BULKIO::StreamSRI tmpH = H;
    RH_SRIMap::iterator currH = currentHs.find(std::string(H.streamID));
    if (currH == currentHs.end()) {
    	if ( sriListener ) (*sriListener)( this, tmpH);
    	currentHs[std::string(H.streamID)] = std::make_pair(tmpH, true);
        if (H.blocking) {
            boost::mutex::scoped_lock lock(dataBufferLock);
            blocking = true;
            queueSem->setCurrValue(workQueue.size());
        }
    } else {
    	if ( sriCmp ) {
	    	if (!sriCmp(tmpH, currH->second.first)) {
	            currentHs[std::string(H.streamID)] = std::make_pair(tmpH, true);
	            if (H.blocking) {
	                boost::mutex::scoped_lock lock(dataBufferLock);
	                blocking = true;
	                queueSem->setCurrValue(workQueue.size());
	            }
	    	}
    	}
    }
}
Example #22
0
File: os.cpp Project: OPSF/uClinux
void MprCmd::outputData()
{
	mprAssert(handle != 0);

	if (outputDataProc == 0) {
		return;
	}

	lock();
	inUse++;
	unlock();

	while (! (flags & MPR_CMD_DISPOSED)) {
		(outputDataProc)(this, data);
	}

	lock();
	if (--inUse == 0) {
		if (task) {
			task->dispose();
		}
		delete this;
	} else {
		unlock();
	}
}
Example #23
0
CString CAmiko::addPaymentRequest(const CString &receipt, uint64_t amount)
{
	//TODO: check number of existing incoming payments.
	//If it's too large, raise an exception.

	CString ID = getSecureRandom(32).hexDump();

	CTransaction t = CTransaction(receipt, amount);
	t.m_nonce = getSecureRandom(TRANSACTION_NONCE_LENGTH);

	{
		CMutexLocker lock(m_Settings);
		t.m_meetingPoint = CRIPEMD160(
			CSHA256(m_Settings.m_Value.m_MeetingPointPubKey).toBinBuffer()
			);
	}

	t.calculateTokenAndHash();

	{
		CMutexLocker lock(m_IncomingPayments);
		m_IncomingPayments.m_Value[ID] = t;
	}

	CMutexLocker lock(m_Settings);
	return m_Settings.m_Value.getPaymentURL(ID);
}
Example #24
0
int 
Actor::recv(Actor*& sender, uint8_t& port, void* buf, size_t size)
{
  // Do not allow receive of other actor queue
  if (s_running != this) return (-1);

  // Check if receiver needs to wait for sending actor
  uint8_t key = lock();
  if (m_sending.is_empty()) {
    m_receiving = true;
    Thread* thread = (Thread*) get_succ();
    detach();
    unlock(key);
    resume(thread);
    key = lock();
  }

  // Copy sender message parameters
  int res = -2;
  sender = (Actor*) m_sending.get_succ();
  port = sender->m_port;
  if (size >= sender->m_size) {
    memcpy(buf, sender->m_buf, sender->m_size);
    res = sender->m_size;
  }
  m_receiving = false;

  // Reschedule the sender
  get_succ()->attach(sender);
  unlock(key);
  return (res);
}
Example #25
0
void 
TTracker::CloseActiveQueryWindows(dev_t device)
{
	// used when trying to unmount a volume - an active query would prevent that from
	// happening
	bool closed = false;
	AutoLock<WindowList> lock(fWindowList);
	for (int32 index = fWindowList.CountItems(); index >= 0; index--) {
		BQueryContainerWindow *window = dynamic_cast<BQueryContainerWindow *>
			(fWindowList.ItemAt(index));
		if (window) {
			AutoLock<BWindow> lock(window);
			if (window->ActiveOnDevice(device)) {
				window->PostMessage(B_CLOSE_REQUESTED);
				closed = true;
			}
		}
	}
	lock.Unlock();
	if (closed)
		for (int32 timeout = 30; timeout; timeout--) {
			// wait a bit for windows to fully close
			if (!QueryActiveForDevice(device))
				return;
			snooze(100000);
		}
}
ScriptObject InjectedScriptManager::createInjectedScript(const String& source, ScriptState* scriptState, int id)
{
    JSLockHolder lock(scriptState);

    SourceCode sourceCode = makeSource(source);
    JSDOMGlobalObject* globalObject = jsCast<JSDOMGlobalObject*>(scriptState->lexicalGlobalObject());
    JSValue globalThisValue = scriptState->globalThisValue();

    JSValue evaluationException;
    JSValue evaluationReturnValue;
    if (isMainThread())
        evaluationReturnValue = JSMainThreadExecState::evaluate(scriptState, sourceCode, globalThisValue, &evaluationException);
    else {
        JSC::JSLockHolder lock(scriptState);
        evaluationReturnValue = JSC::evaluate(scriptState, sourceCode, globalThisValue, &evaluationException);
    }
    if (evaluationException)
        return ScriptObject();

    JSValue functionValue = evaluationReturnValue;
    CallData callData;
    CallType callType = getCallData(functionValue, callData);
    if (callType == CallTypeNone)
        return ScriptObject();

    MarkedArgumentBuffer args;
    args.append(toJS(scriptState, globalObject, m_injectedScriptHost.get()));
    args.append(globalThisValue);
    args.append(jsNumber(id));

    JSValue result = JSC::call(scriptState, functionValue, callType, callData, globalThisValue, args);
    if (result.isObject())
        return ScriptObject(scriptState, result.getObject());
    return ScriptObject();
}
Example #27
0
void LDA<Scalar>::doc_e_step_worker() {
    std::shared_ptr<corpus::Corpus> corpus;
    size_t index;

    while (true) {
        // extract a job
        {
            std::lock_guard<std::mutex> lock(queue_in_mutex_);
            if (queue_in_.empty())
                break;
            std::tie(corpus, index) = queue_in_.front();
            queue_in_.pop_front();
        }

        // do said job
        auto vp = e_step_->doc_e_step(
            corpus->at(index),
            model_parameters_
        );

        // show some results
        {
            std::lock_guard<std::mutex> lock(queue_out_mutex_);
            queue_out_.emplace_back(vp, index);
        }
        // talk about those results
        queue_out_cv_.notify_one();
    }
}
Example #28
0
 std::string GetFastFileHash(const std::string & filename)
 {
     FileHashResultPtr fileHashResultPtr;
     {
         AutoMutex lock(g_fastFileHashCache_mutex);
         FileCacheMap::iterator iter = g_fastFileHashCache.find(filename);
         if(iter != g_fastFileHashCache.end())
         {
             fileHashResultPtr = iter->second;
         }
         else
         {
             fileHashResultPtr = FileHashResultPtr(new FileHashResult);
             g_fastFileHashCache[filename] = fileHashResultPtr;
         }
     }
     
     std::string hash;
     {
         AutoMutex lock(fileHashResultPtr->mutex);
         if(!fileHashResultPtr->ready)
         {
             fileHashResultPtr->ready = true;
             fileHashResultPtr->hash = ComputeHash(filename);
         }
         
         hash = fileHashResultPtr->hash;
     }
     
     return hash;
 }
Notification* PriorityNotificationQueue::waitDequeueNotification(long milliseconds)
{
    Notification::Ptr pNf;
    WaitInfo* pWI = 0;
    {
        FastMutex::ScopedLock lock(_mutex);
        pNf = dequeueOne();
        if (pNf) return pNf.duplicate();
        pWI = new WaitInfo;
        _waitQueue.push_back(pWI);
    }
    if (pWI->nfAvailable.tryWait(milliseconds))
    {
        pNf = pWI->pNf;
    }
    else
    {
        FastMutex::ScopedLock lock(_mutex);
        pNf = pWI->pNf;
        for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it)
        {
            if (*it == pWI)
            {
                _waitQueue.erase(it);
                break;
            }
        }
    }
    delete pWI;
    return pNf.duplicate();
}
void threadedOpticalFlow::threadedFunction(){
    while(isThreadRunning()){

        lock();
        
        if(!bFlowDirty){
            condition.wait(mutex);
        }
        
        swap(pixelsIn, pixelsInBack);
        // now we can modify pixelsInBack without affecting the calculaton of the flow
        
        unlock();
        
        if(blurSize > 0){
            ofxCv::blur(pixelsIn, pixelsInBlurred, blurSize);
            flow.calcOpticalFlow(pixelsInBlurred);
        }else{
            flow.calcOpticalFlow(pixelsIn);
        }
        
        lock();
        
        // testing...
//        pixelsFlow.allocate(flow.getWidth(), flow.getHeight(), 2);
        //
        
//        memcpy(pixelsFlow.getPixels(), flow.getFlow().ptr<float>(), flow.getWidth() * flow.getHeight() * pixelsFlow.getBytesPerPixel());
        
        bFlowDirty = false;
        bNewPixels = true;
        
        unlock();
    }
}