当前位置: 首页>>代码示例>>C++>>正文


C++ ConditionVariable类代码示例

本文整理汇总了C++中ConditionVariable的典型用法代码示例。如果您正苦于以下问题:C++ ConditionVariable类的具体用法?C++ ConditionVariable怎么用?C++ ConditionVariable使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ConditionVariable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: assert

int
WinMonitorData::RegisterCondition( unsigned int cvid )
{
    int ret = -1;

    assert( hMutex != NULL );

    // check if there is already a condition associated with the chosen id
    if( cvmap[cvid] == NULL )
    {
        // there was no condition already associated with this condition var
        // build one
        ConditionVariable* newcv = new ConditionVariable( hMutex );

        // initialize the condition variable
        if( newcv->Init() == 0 )
        {
            cvmap[cvid] = newcv;
            ret = 0;
        }
        else
        {
            // failed to initialized - release the object
            delete newcv;
        }
    }
    return ret;
}
开发者ID:bwelton,项目名称:mrnet,代码行数:28,代码来源:Monitor-win.C

示例2: if

        void Algorithm::RunParallel(set<Algorithm*> algos, Graph& G, vector<string> parameters,
                                    float MaxApproximationDistance, float MinCorrectnessProbability)
        {
            set<Algorithm*> SelectedAlgorithms;
            for(set<Algorithm*>::iterator i = algos.begin(); i != algos.end(); i++)
                if((*i)->SuitableFor(G)
                && (*i)->CanGuaranteeApproximationDistance(G, MaxApproximationDistance)
                && (*i)->CanGuaranteeCorrectnessProbability(G, MinCorrectnessProbability))
                    SelectedAlgorithms.insert(*i);

            if(SelectedAlgorithms.size() == 0)
            {
                throw "No suitable algorithm found";
            }
            else if(SelectedAlgorithms.size() == 1) // we have 1 algorithm => no multithreading needed
            {
                Algorithm* algo = *SelectedAlgorithms.begin();
                algo->Run(G, parameters);
            }
            else
            {
                // we have more than 1 algorithm => run them in parallel

                // give each algorithm its own copy of G
                map<Thread*, Graph*> GraphCopies;
                for(set<Algorithm*>::iterator i = SelectedAlgorithms.begin(); i != SelectedAlgorithms.end(); i++)
                    GraphCopies[*i] = new Graph(G);


                ConditionVariable synchronize;
                Thread* finishedAlgorithm = NULL;
                synchronize.Lock();

                cerr << "starting " << SelectedAlgorithms.size() << " of " << algos.size() << " algorithms\n";
                for(set<Algorithm*>::iterator i = SelectedAlgorithms.begin(); i != SelectedAlgorithms.end(); i++)
                    (*i)->RunInThread(GraphCopies[*i], parameters, &synchronize, &finishedAlgorithm);


                while(finishedAlgorithm == NULL) // a mislead interrupt can cause the Wait to stop, therefore
                    synchronize.Wait(); // this has to be in a loop that checks whether someone has actually finished
                G = *(GraphCopies[finishedAlgorithm]);


                cerr << "someone finished. sending termination requests\n";
                for(set<Algorithm*>::iterator i = SelectedAlgorithms.begin(); i != SelectedAlgorithms.end(); i++)
                    (*i)->Terminate();
                synchronize.Unlock();

                cerr << "waiting for threads to join\n";
                for(set<Algorithm*>::iterator i = SelectedAlgorithms.begin(); i != SelectedAlgorithms.end(); i++)
                {
                    (*i)->Join();
                    delete GraphCopies[*i];
                }
                GraphCopies.clear();
                cerr << "everyone joined\n";
            }
        }
开发者ID:OpenGraphtheory,项目名称:OpenGraphtheory,代码行数:58,代码来源:algorithms.cpp

示例3: assert

void Thread::sleep(int ms) {
  assert(ms >= 0);
  if (ms > 0) {
#ifdef WIN32
    Sleep(ms);
#else
    ConditionVariable sleeper;
    sleeper.acquire();
    sleeper.timedWait(ms);
    sleeper.release();
#endif
  } else if ( ms == 0 )
    yield();
}
开发者ID:exploreHNC,项目名称:gnelib,代码行数:14,代码来源:Thread.cpp

示例4: testConditionVariable

/*
 * Check that a condition variable works
 */
void ThreadTest::testConditionVariable() {
  Mutex mutex;
  ConditionVariable condition;
  MockConditionThread thread(&mutex, &condition);
  thread.Start();

  mutex.Lock();
  if (thread.i != MockConditionThread::EXPECTED) {
    condition.Wait(&mutex);
  }
  OLA_ASSERT_EQ(10, thread.i);
  mutex.Unlock();

  thread.Join();
}
开发者ID:sl1200mk2,项目名称:ola,代码行数:18,代码来源:ThreadTest.cpp

示例5: Create

 ConditionVariable* ConditionVariable::Create()
 {
     ConditionVariable* ptr = new ConditionVariable;
     if (!ptr) {
         return nullptr;
     }
     
     const int error = ptr->Construct();
     if (error) {
         delete ptr;
         return nullptr;
     }
     
     return ptr;
 }
开发者ID:chenjianjun571,项目名称:cioforandroid,代码行数:15,代码来源:ConditionVariable.cpp

示例6: ConditionVariable

Condition* ConditionVariable::load(QDomElement* root)
{
    QDomElement elem = root->firstChildElement();

    ConditionVariable* condition = new ConditionVariable();

    while(!elem.isNull())
    {
        if(elem.tagName().toLower().compare("name") == 0)
        {
            condition->setVarName( elem.text().toStdString() );
        }
        else if(elem.tagName().toLower().compare("value") == 0)
        {
            condition->setTriggerValue( elem.text().toInt() );
        }
        else if(elem.tagName().toLower().compare("trigger") == 0)
        {
            QString trigger = elem.text().toLower();
            if( trigger.compare("equal") == 0)
                condition->setTrigger(Equal);
            else if( trigger.compare("nolongerequal") == 0)
                condition->setTrigger(NoLongerEqual);
            else if( trigger.compare("greaterthan") == 0)
                condition->setTrigger(GreaterThan);
            else if( trigger.compare("lessthan") == 0)
                condition->setTrigger(LessThan);
        }

        elem = elem.nextSiblingElement();
    }

    return condition;
}
开发者ID:appl,项目名称:RASP,代码行数:34,代码来源:ConditionVariable.cpp

示例7: while

status_t
DPCQueue::_Thread()
{
	while (true) {
		InterruptsSpinLocker locker(fLock);

		// get the next pending callback
		DPCCallback* callback = fCallbacks.RemoveHead();
		if (callback == NULL) {
			// nothing is pending -- wait unless the queue is already closed
			if (_IsClosed())
				break;

			ConditionVariableEntry waitEntry;
			fPendingCallbacksCondition.Add(&waitEntry);

			locker.Unlock();
			waitEntry.Wait();

			continue;
		}

		callback->fInQueue = NULL;
		fCallbackInProgress = callback;

		// call the callback
		locker.Unlock();
		callback->DoDPC(this);
		locker.Lock();

		fCallbackInProgress = NULL;

		// wake up threads waiting for the callback to be done
		ConditionVariable* doneCondition = fCallbackDoneCondition;
		fCallbackDoneCondition = NULL;
		locker.Unlock();
		if (doneCondition != NULL)
			doneCondition->NotifyAll();
	}

	return B_OK;
}
开发者ID:SummerSnail2014,项目名称:haiku,代码行数:42,代码来源:DPC.cpp

示例8: ConsumerThread

void ConsumerThread(int id)
{
	LOG("Starting consumer thread " << id);
    for(;;)
    {
        {
            Mutex::Lock __(ItemBufferLock);

            while(QueueSize == 0 && !StopRequested)
                ItemBufferNotEmpty.Wait(ItemBufferLock);

            if(StopRequested && QueueSize == 0)
                break;

			int Item = ItemBuffer[QueueStartOffset];
			QueueSize--;
			QueueStartOffset++;
			TotalItemsConsumed++;

            if(QueueStartOffset == BUFFER_SIZE)
				QueueStartOffset = 0;

			LOG("Consumer " << id << ", item " << Item << ", queue size " << QueueSize);
        }

		ItemBufferNotFull.Signal();
        Sleep(Random(CONSUMER_SLEEP_TIME_MS));
    }

	LOG("Consumer exiting");
}
开发者ID:AbdelghaniDr,项目名称:mirror,代码行数:31,代码来源:ConditionVariable.cpp

示例9: ProducerThread

void ProducerThread()
{
	LOG("Starting producer thread");
    for(;;) {
		Sleep(Random(PRODUCER_SLEEP_TIME_MS));
		{
			Mutex::Lock __(ItemBufferLock);
	
			while(QueueSize == BUFFER_SIZE && !StopRequested)
				ItemBufferNotFull.Wait(ItemBufferLock);
	
	        if(StopRequested)
	            break;
	
			int Item = Random(1000);

	        ItemBuffer[(QueueStartOffset + QueueSize) % BUFFER_SIZE] = Item;
	        QueueSize++;
	        TotalItemsProduced++;
	        
	        LOG("Producer item " << Item << ", queue size " << QueueSize);
		}
		ItemBufferNotEmpty.Signal();
    }
	LOG("Producer exiting");
}
开发者ID:AbdelghaniDr,项目名称:mirror,代码行数:26,代码来源:ConditionVariable.cpp

示例10: user_memcpy

static status_t
acpi_battery_control(void* _cookie, uint32 op, void* arg, size_t len)
{
	battery_device_cookie* device = (battery_device_cookie*)_cookie;
	status_t err;

	switch (op) {
		case IDENTIFY_DEVICE: {
			if (len < sizeof(uint32))
				return B_BAD_VALUE;

			uint32 magicId = kMagicACPIBatteryID;
			return user_memcpy(arg, &magicId, sizeof(magicId));
		}

		case GET_BATTERY_INFO: {
			if (len < sizeof(acpi_battery_info))
				return B_BAD_VALUE;

			acpi_battery_info batteryInfo;
			err = ReadBatteryStatus(device->driver_cookie, &batteryInfo);
			if (err != B_OK)
				return err;
			return user_memcpy(arg, &batteryInfo, sizeof(batteryInfo));
		}

		case GET_EXTENDED_BATTERY_INFO: {
			if (len < sizeof(acpi_extended_battery_info))
				return B_BAD_VALUE;

			acpi_extended_battery_info extBatteryInfo;
			err = ReadBatteryInfo(device->driver_cookie, &extBatteryInfo);
			if (err != B_OK)
				return err;
			return user_memcpy(arg, &extBatteryInfo, sizeof(extBatteryInfo));
		}

		case WATCH_BATTERY:
			sBatteryCondition.Wait();
			if (atomic_get(&(device->stop_watching))) {
				atomic_set(&(device->stop_watching), 0);
				return B_ERROR;
			}
			return B_OK;

		case STOP_WATCHING_BATTERY:
			atomic_set(&(device->stop_watching), 1);
			sBatteryCondition.NotifyAll();
			return B_OK;
	}

	return B_DEV_INVALID_IOCTL;
}
开发者ID:DonCN,项目名称:haiku,代码行数:53,代码来源:acpi_battery.cpp

示例11: if

void
PhysicalPageSlotQueue::PutSlot(PhysicalPageSlot* slot)
{
	InterruptsLocker locker;

	slot->next = fSlots;
	fSlots = slot;

	if (slot->next == NULL)
		fFreeSlotCondition.NotifyAll();
	else if (slot->next->next == NULL)
		fFreeSlotCondition.NotifyAll();
}
开发者ID:SummerSnail2014,项目名称:haiku,代码行数:13,代码来源:x86_physical_page_mapper_large_memory.cpp

示例12: run

static void run(void* args) {
    //assume args is an int
    int value = *(int*)args;

    mtx.acquire();
    while(counter != value) {
//		std::cout << "OOOOPSSS Not my turn: " << value << endl;
        cv.wait(mtx);
    }

    cout << "This is run #" <<  value << endl;
    counter++;
//	kThread::currentKT->currentUT->migrate(cluster);
    cv.signalAll(mtx);
}
开发者ID:samanbarghi,项目名称:uThreads,代码行数:15,代码来源:ConditionVariable.cpp

示例13:

void
Inode::NotifyEndClosed(bool writer)
{
	TRACE("Inode %p::%s(%s)\n", this, __FUNCTION__,
		writer ? "writer" : "reader");

	if (writer) {
		// Our last writer has been closed; if the pipe
		// contains no data, unlock all waiting readers
		TRACE("  buffer readable: %zu\n", fBuffer.Readable());
		if (fBuffer.Readable() == 0) {
			ReadRequestList::Iterator iterator = fReadRequests.GetIterator();
			while (ReadRequest* request = iterator.Next())
				request->Notify();

			if (fReadSelectSyncPool)
				notify_select_event_pool(fReadSelectSyncPool, B_SELECT_READ);
		}
	} else {
		// Last reader is gone. Wake up all writers.
		fWriteCondition.NotifyAll();

		if (fWriteSelectSyncPool) {
			notify_select_event_pool(fWriteSelectSyncPool, B_SELECT_WRITE);
			notify_select_event_pool(fWriteSelectSyncPool, B_SELECT_ERROR);
		}
	}
}
开发者ID:mylegacy,项目名称:haiku,代码行数:28,代码来源:fifo.cpp

示例14: _

static status_t
low_resource_manager(void*)
{
	bigtime_t timeout = kLowResourceInterval;
	while (true) {
		int32 state = low_resource_state_no_update(B_ALL_KERNEL_RESOURCES);
		if (state != B_LOW_RESOURCE_CRITICAL) {
			acquire_sem_etc(sLowResourceWaitSem, 1, B_RELATIVE_TIMEOUT,
				timeout);
		}

		RecursiveLocker _(&sLowResourceLock);

		compute_state();
		state = low_resource_state_no_update(B_ALL_KERNEL_RESOURCES);

		TRACE(("low_resource_manager: state = %ld, %ld free pages, %lld free "
			"memory, %lu free semaphores\n", state, vm_page_num_free_pages(),
			vm_available_not_needed_memory(),
			sem_max_sems() - sem_used_sems()));

		if (state < B_LOW_RESOURCE_NOTE)
			continue;

		call_handlers(sLowResources);

		if (state == B_LOW_RESOURCE_WARNING)
			timeout = kWarnResourceInterval;
		else
			timeout = kLowResourceInterval;

		sLowResourceWaiterCondition.NotifyAll();
	}
	return 0;
}
开发者ID:mmanley,项目名称:Antares,代码行数:35,代码来源:low_resource_manager.cpp

示例15: putBuffer

  bool putBuffer()
  {
    Lock<Mutex> _(_dataAccessMutex);

    if(_inUseBuffers.size() >= MAX_BUFFER_COUNT)
    {
      logger(LOG_WARNING) << "USBBulkStreamer: Dropping a frame because of slow forward pipeline." << std::endl;
      _inUseBuffers.pop_front();
    }

    auto f = _rawBuffers.get();

    RawDataFramePtr &raw = *f;

    if(!raw || raw->data.size() != usbBuffer.size())
    {
      raw = RawDataFramePtr(new RawDataFrame());
      raw->data.resize(usbBuffer.size());
    }

    memcpy(raw->data.data(), usbBuffer.data(), usbBuffer.size() - BULK_XFER_EXTRA_SIZE);

    raw->timestamp = _timer.getCurentRealTime(); // in micro seconds
    
    _inUseBuffers.push_back(f);

    _dataAvailableCondition.notify_all();

    return true;
  }
开发者ID:Metrilus,项目名称:voxelsdk,代码行数:30,代码来源:USBBulkStreamer.cpp


注:本文中的ConditionVariable类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。