Beispiel #1
0
int main (int argc, char *argv[]){

	Queue q = newQueue();

	assert(queueEmpty(q));

	queueJoin(q, 5);
	queueJoin(q, 8);
	queueJoin(q, 3);
	queueJoin(q, 9);
	queueJoin(q, 2);

	printQueue(q);

	assert(!queueEmpty(q));

	assert(queueLeave(q) == 5);
	assert(queueLeave(q) == 8);
	assert(queueLeave(q) == 3);
	assert(queueLeave(q) == 9);
	assert(queueLeave(q) == 2);

	assert(queueEmpty(q));

	dropQueue(q);

	return EXIT_SUCCESS;
}
void Simulation(const double simTime, const double meanInterval, 
		const double meanServiceTime, const int verbose) {

	double currentTime = 0;				// The simulation clock!
	//	int serving = 0;					// TRUE if a customer is currently being served

        initQueue();

	while (currentTime < simTime || ! queueEmpty()) {

		Customer current, next;
		double finishTime;

		if (queueEmpty()) {
			current = GetNextArrival(meanInterval, meanServiceTime, verbose);
			if (current.arrivalTime >= simTime)
				break;		// We are done. The next arrival comes too late
			currentTime = current.startTime = current.arrivalTime;	// update the current
												// to the start of this arrival
		} else {
			dequeue(&current);
			if (current.arrivalTime > currentTime)
				currentTime = current.arrivalTime;
			current.startTime = currentTime;	// start now!
			
		}	//	if (queueEmpty() ... else ...

		finishTime = current.startTime + current.serviceTime;
		if (verbose)
			printf("Customer that arrived at %0.2f starting service at %0.2f.\n", 
				current.arrivalTime, current.startTime);
		
		//	Now allow more customers to arrive while the current one is being served
		do {
			next = GetNextArrival(meanInterval, meanServiceTime, verbose);
			if (next.arrivalTime < simTime)
				enqueue(next);
		} while (next.arrivalTime < finishTime && next.arrivalTime < simTime);
		
		//	Now we can step the clock ahead to the finish time of the current customer
		currentTime = finishTime;
		if (verbose)
			printf("Customer that started at %0.2f finished at %0.2f.\n", 
				current.startTime, finishTime);
		GatherStatistics(current, verbose);

	}	// while (currentTime < simTime ...)

}	// void Simulation(...)
Beispiel #3
0
JausBoolean scManagerTerminateServiceConnection(NodeManagerInterface nmi, ServiceConnection deadSc)
{
	TerminateServiceConnectionMessage terminateSc;
	JausMessage txMessage;
	ServiceConnection prevSc = NULL;
	ServiceConnection sc = NULL;

	pthread_mutex_lock(&nmi->scm->mutex);

	sc = nmi->scm->incomingSc;
	while(sc)
	{
		if(sc->commandCode == deadSc->commandCode && jausAddressEqual(sc->address, deadSc->address) )
		{
			if(sc->instanceId > -1)
			{
				terminateSc = terminateServiceConnectionMessageCreate();
				jausAddressCopy(terminateSc->source, nmi->cmpt->address);
				jausAddressCopy(terminateSc->destination, deadSc->address);
				terminateSc->serviceConnectionCommandCode = deadSc->commandCode;
				terminateSc->instanceId = deadSc->instanceId;

				txMessage = terminateServiceConnectionMessageToJausMessage(terminateSc);
				nodeManagerSend(nmi, txMessage);
				jausMessageDestroy(txMessage);

				terminateServiceConnectionMessageDestroy(terminateSc);
			}

			// Set SC to inactive
			sc->isActive = JAUS_FALSE;

			// Empty any Remaining Queue
			queueEmpty(sc->queue, (void *)jausMessageDestroy);

			// Remove Service Connection
			if(prevSc)
			{
				prevSc->nextSc = sc->nextSc;
				sc->nextSc = NULL;
			}
			else
			{
				nmi->scm->incomingSc = sc->nextSc;
				sc->nextSc = NULL;
			}

			nmi->scm->incomingScCount--;
			pthread_mutex_unlock(&nmi->scm->mutex);
			return JAUS_TRUE;
		}
		else
		{
			prevSc = sc;
			sc = sc->nextSc;
		}
	}
	pthread_mutex_unlock(&nmi->scm->mutex);
	return JAUS_FALSE;
}
void BackgroundWorkerQueue::_tryNextItemInQueue()
{
//    DLog("Try next item");
    if( this->_getIsRunnableActive() ) {
        return;
    }

    _queueMutex.lock();
    RunnableItem *currRunnable = NULL;
    if( !_runnableQueue.isEmpty() ) {
         currRunnable = _runnableQueue.dequeue();
    }
    _queueMutex.unlock();

    if(currRunnable == NULL) {
        // no more items
//        DLog("No more items");
        Q_EMIT queueEmpty();
        return;
    }

    connect(currRunnable, SIGNAL(finishedWithWork()), this, SLOT(_currentItemFinishedWithWork()));
    QThreadPool::globalInstance()->start(currRunnable);
//    DLog("Work started");

    this->_setIsRunnableActive(true);
}
Beispiel #5
0
bool queue::push(list_value *val){
	if (val == NULL)
		return false;
	if (queueEmpty()){
		head = val;
		body = head;
	}
		
	else{
		body->next = val;
		val->next = NULL;
		body = val;
	}
	body->next = NULL;
	
	/*auto v = new list_value();
	v->x = val->x;
	v->y = val->y;
	body->next = v;
	v->next = NULL;
	body = v;*/
	
	
	length++;
	return true;
}
Beispiel #6
0
void AnalysisFeature::analyzeTracks(QList<int> trackIds) {
    if (m_pAnalyserQueue == NULL) {
        // Save the old BPM detection prefs setting (on or off)
        m_iOldBpmEnabled = m_pConfig->getValueString(ConfigKey("[BPM]","BPMDetectionEnabled")).toInt();
        // Force BPM detection to be on.
        m_pConfig->set(ConfigKey("[BPM]","BPMDetectionEnabled"), ConfigValue(1));
        // Note: this sucks... we should refactor the prefs/analyser to fix this hacky bit ^^^^.

        m_pAnalyserQueue = AnalyserQueue::createAnalysisFeatureAnalyserQueue(m_pConfig, m_pTrackCollection);

        connect(m_pAnalyserQueue, SIGNAL(trackProgress(int)),
                m_pAnalysisView, SLOT(trackAnalysisProgress(int)));
        connect(m_pAnalyserQueue, SIGNAL(trackFinished(int)),
                m_pAnalysisView, SLOT(trackAnalysisFinished(int)));

        connect(m_pAnalyserQueue, SIGNAL(queueEmpty()),
                this, SLOT(cleanupAnalyser()));
        emit(analysisActive(true));
    }

    foreach(int trackId, trackIds) {
        TrackPointer pTrack = m_pTrackCollection->getTrackDAO().getTrack(trackId);
        if (pTrack) {
            //qDebug() << this << "Queueing track for analysis" << pTrack->getLocation();
            m_pAnalyserQueue->queueAnalyseTrack(pTrack);
        }
    }
Beispiel #7
0
//This implementation has a tight loop and very inefficient polling mechanism
void * getQueue(MessageQue * pMsgQue)
{
	void *pTemp = NULL;
	while(1)
	{
		if (queueEmpty(pMsgQue->pQueue))
			continue;
		pthread_mutex_lock(&pMsgQue->queLock);
		if (!queueEmpty(pMsgQue->pQueue))
		{
			pTemp = dequeue(pMsgQue->pQueue);
			pthread_mutex_unlock(&pMsgQue->queLock);
			return (pTemp);
		}
		pthread_mutex_unlock(&pMsgQue->queLock);
	}
}
Beispiel #8
0
bool ValidateGameField() {
	/*проверка поля для игры:
		каждая ячейка должна быть доступна минимум с 2х сторон (чтобы не было тупиков)
		поле должно быть связным (чтобы не было недосягаемых, огороженных со всех сторон участков)
	*/
	printf("Validate game field...\n");

	int k = 0;
	for (int i = 0; i < GAME_ROWS; i++) {
		for (int j = 0; j < GAME_COLS; j++) {
			checked[i][j] = 0;
			k = 0;
			for (int l = 0; l < 4; l++) {
				if (isCellReachable(j, i, l)) {
					k++;
				}
			}
			if (k < 2) {
				printf("Bad field for game: dead end at (y = %d, x = %d)\n", i, j);
				checked[i][j] = 1;
				return false;
			}
		}
	}

	//проверка связности поля алгоритмом, напоминающим поиск в ширину в графе
	qhead = 0;
	qtail = 0;
	queuePush(0, 0);
	int cx, cy;
	int rx, ry;
	while (!queueEmpty()) {
		queueTake(&cx, &cy);
		checked[cy][cx] = 1;
		for (int i = 1; i < 5; i++) {
			if (!isCellReachable(cx, cy, i % 4)) {
				continue;
			}
			getViewingCell(cx, cy, i % 4, &rx, &ry);
			if (checked[ry][rx] == 1) {
				continue;
			}
			queuePush(rx, ry);
		}
	}

	printf("\n");
	for (int i = 0; i < GAME_ROWS; i++) {
		for (int j = 0; j < GAME_COLS; j++) {
			if (checked[i][j] == 0) {
				printf("Bad field for game: unreachable cell at (y = %d, x = %d)\n", i, j);
				return false;
			}
		}
	}
	
	return true;
}
Beispiel #9
0
JausBoolean scManagerReceiveServiceConnection(NodeManagerInterface nmi, ServiceConnection requestSc, JausMessage *message)
{
	ServiceConnection prevSc;
	ServiceConnection sc;

	pthread_mutex_lock(&nmi->scm->mutex);

	sc = nmi->scm->incomingSc;
	prevSc = NULL;
	while(sc)
	{
		if(sc->commandCode == requestSc->commandCode && jausAddressEqual(sc->address, requestSc->address) )
		{
			if(ojGetTimeSec() > (sc->lastSentTime + sc->timeoutSec))
			{
				// Connection has Timed Out
				sc->isActive = JAUS_FALSE;
				queueEmpty(sc->queue, (void *)jausMessageDestroy);

				// Remove Service Connection
				if(prevSc)
				{
					prevSc->nextSc = sc->nextSc;
					sc->nextSc = NULL;
				}
				else
				{
					nmi->scm->incomingSc = sc->nextSc;
					sc->nextSc = NULL;
				}
				nmi->scm->incomingScCount--;
				pthread_mutex_unlock(&nmi->scm->mutex);
				return JAUS_FALSE;
			}

			if(sc->queue->size)
			{
				*message = (JausMessage)queuePop(sc->queue);
				pthread_mutex_unlock(&nmi->scm->mutex);
				return JAUS_TRUE;
			}
			else
			{
				pthread_mutex_unlock(&nmi->scm->mutex);
				return JAUS_FALSE;
			}
		}
		else
		{
			prevSc = sc;
			sc = sc->nextSc;
		}
	}

	pthread_mutex_unlock(&nmi->scm->mutex);
	return JAUS_FALSE;
}
T& MinHblt<T>::RemoveMin() {
    if (root_ == NULL)
        throw queueEmpty();
    HbltNode<T> *left = root_->left_;
    HbltNode<T> *right = root_->right_;
    T& min = root_->element_;
    delete root_;
    root_ = left;
    Meld(root_, right);
    size_--;
    return min;
}
StreamToFileManager::StreamToFileManager(QObject *parent) :
    QObject(parent),
    _chunkCounter(0),
    _targetFile(NULL),
    _isStreamingAborted(false)
{
    _bufferedTransmitter = new BufferedTransmitter(1024 * 1024 * 2, this); // 2MB
    connect(_bufferedTransmitter, SIGNAL(bufferFlush(QByteArray)), this, SLOT(_bufferTransmitterFlush(QByteArray)));

    _backgroundWorkerQueue = new BackgroundWorkerQueue(this);
    connect(_backgroundWorkerQueue, SIGNAL(queueEmpty()), this, SLOT(_executorQueueEmtpy()));
}
Beispiel #12
0
unsigned char queueGet(Queue *q)
{
	if (queueEmpty(q))
		return 0xFF;
	else {
		unsigned char c = q->buf[q->out];
		q->out++;
		q->cnt--;
		if(q->out == q->size)
			q->out = 0;
		return c;
	}
}
Beispiel #13
0
void queueDestroy(Queue queue, void (*objectDestroy)(void *))
{
    if(queue == NULL)
    {
        return;
    }

    queueEmpty(queue, objectDestroy);

    pthread_mutex_destroy(&queue->mutex);

    free(queue);
}
int main() {
    Queue *queue = malloc(sizeof(Queue));
    queueCreate(queue, 10);
    queuePush(queue, 1);
    queuePush(queue, 2);
    queuePush(queue, 3);
    queuePop(queue);
    queuePop(queue);
    assert(queuePeek(queue) == 3);
    assert(queueEmpty(queue) == 0);
    queueDestroy(queue);

    return 0;
}
Beispiel #15
0
void queueRemove (tQueue* q) {
/*
** Odstraní znak ze zaèátku fronty q. Pokud je fronta prázdná, o¹etøete
** vzniklou chybu voláním funkce queueError(QERR_REMOVE).
** Hodnotu na uvolnìné pozici ve frontì nijak neo¹etøujte (nepøepisujte).
** Pøi implementaci vyu¾ijte døíve definované funkce queueEmpty a nextIndex.
*/

    if(queueEmpty(q)){              // Zkontroluj, zda-li neni fronte prazdna
        queueError(QERR_REMOVE);    // Vyhod chybovou hlasku
        return;                     // Ukonci
    }
    q->f_index = nextIndex(q->f_index);     // Odstran znak ze zacatku fronty
}
Beispiel #16
0
void queueRemove (tQueue* q) {
/*
** Odstraní znak ze zaèátku fronty q. Pokud je fronta prázdná, o¹etøete
** vzniklou chybu voláním funkce queueError(QERR_REMOVE).
** Hodnotu na uvolnìné pozici ve frontì nijak neo¹etøujte (nepøepisujte).
** Pøi implementaci vyu¾ijte døíve definované funkce queueEmpty a nextIndex.
*/
	if (queueEmpty(q))
	{
		queueError(QERR_REMOVE);
		return;
	}
	q->f_index = nextIndex(q->f_index);		/* Indexom prvého prvku sa stáva prvok za aktuálnym f_index */
}
Beispiel #17
0
// 层序递归遍历T(利用队列),对每个结点调用函数visit一次且仅一次
void levelOrderTraverse(BiTreeLink T,int(*visit)(TElemType)){
	LinkQueue q;
	QElemType a;
	if(T){
		initQueue(&q);
		enQueue(&q,T);//队列不空
		while(!queueEmpty(q)){
			deQueue(&q,&a);//出队列
			(*visit)(a->data);//访问元素
			if(a->lchild!=NULL)	enQueue(&q,a->lchild);
			if(a->rchild!=NULL) enQueue(&q,a->rchild);
		}
		printf("\n");
	}
}
void rbtreeToDot(RBTree tree, const char* racine, const char* dossier) {
	assert(!rbtreeEmpty(tree));	
	
	static int numerofichier=0;
	char final[30];
	sprintf(final,"%s/%s%d.dot",dossier,racine,numerofichier++);
	FILE*fd = fopen(final,"wt");
	
	fprintf(fd,"digraph G { \n");
	
	Node node;
	QUEUE queue;
	queueCreate(&queue);
	queueAdd(queue,rbfirst(tree));
	do {
		node = queueRemove(queue);

		if(node->color==red)
			fprintf(fd,"\t%d [color=red];\n",keyPut(node->key));
		else
			fprintf(fd,"\t%d [color=black];\n",keyPut(node->key));

		if(node->left != tree->nil) {
			fprintf(fd,"\t%d -> %d;\n",keyPut(node->key),keyPut(node->left->key));
			if(node->left->color==red)
				fprintf(fd,"\t%d [color=red];\n",keyPut(node->left->key));
			else
				fprintf(fd,"\t%d [color=black];\n",keyPut(node->left->key));
		}
		if(node->right != tree->nil) {
			fprintf(fd,"\t%d -> %d;\n",keyPut(node->key),keyPut(node->right->key));
			if(node->right->color==red)
				fprintf(fd,"\t%d [color=red];\n",keyPut(node->right->key));
			else
				fprintf(fd,"\t%d [color=black];\n",keyPut(node->right->key));
		}


		if(node->left != tree->nil)
			queueAdd(queue,node->left);
		if(node->right != tree->nil)
			queueAdd(queue,node->right);

	} while(!queueEmpty(queue));

	fprintf(fd,"}\n");
	fclose(fd);
}
Beispiel #19
0
//返回二叉树T中指向元素值为s的结点的指针
BiTreeLink point(BiTreeLink T,TElemType s){
	LinkQueue q;
	QElemType a;
	if(T){//非空树
		initQueue(&q);//初始化队列
		enQueue(&q,T);//根结点入队
		while(!queueEmpty(q)){//队列不空
			deQueue(&q,&a);//出队,队列元素赋给a
			if(a->data==s) return a;
			//有左孩子
			if(a->lchild) enQueue(&q,a->lchild);//入队左孩子
			if(a->rchild) enQueue(&q,a->rchild);//入队右孩子
		}
	}
	return NULL;
}
Beispiel #20
0
void queueRemove (tQueue* q) {
/*
** Odstran znak ze zatku fronty q. Pokud je fronta przdn, oetete
** vzniklou chybu volnm funkce queueError(QERR_REMOVE).
** Hodnotu na uvolnn pozici ve front nijak neoetujte (nepepisujte).
** Pi implementaci vyuijte dve definovan funkce queueEmpty a nextIndex.
*/
    if(queueEmpty(q) == 0)
    {
        q->f_index = nextIndex(q->f_index);
    }
    else
    {
        queueError(QERR_REMOVE);
    }
}
Beispiel #21
0
void queueRemove (tQueue* q) {
/*
** Odstraní znak ze zaèátku fronty q. Pokud je fronta prázdná, o¹etøete
** vzniklou chybu voláním funkce queueError(QERR_REMOVE).
** Hodnotu na uvolnìné pozici ve frontì nijak neo¹etøujte (nepøepisujte).
** Pøi implementaci vyu¾ijte døíve definované funkce queueEmpty a nextIndex.
*/
	if(queueEmpty(q) == 0) //fronta nie je prazdna
	{
		q->f_index = nextIndex(q->f_index); //posunieme sa
	}
	else //fronta je prazdna
	{
		queueError(QERR_REMOVE);
	}
}
Beispiel #22
0
void queueGet (tQueue* q, char* c) {
/*
** Odstraní znak ze zaèátku fronty a vrátí ho prostøednictvím parametru c.
** Pokud je fronta prázdná, o¹etøete to voláním funkce queueError(QERR_GET).
**
** Pøi implementaci vyu¾ijte døíve definovaných funkcí queueEmpty,
** queueFront a queueRemove.
*/

    if(queueEmpty(q)){              // Zkontroluj, zda-li neni fronte prazdna
        queueError(QERR_GET);       // Vyhod chybovou hlasku
        return;                     // Ukonci
    }
    queueFront(q, c);               // Vrat znak
    queueRemove(q);                 // A odstran ho
}
Beispiel #23
0
void queueGet (tQueue* q, char* c) {
/*
** Odstraní znak ze zaèátku fronty a vrátí ho prostøednictvím parametru c.
** Pokud je fronta prázdná, o¹etøete to voláním funkce queueError(QERR_GET).
**
** Pøi implementaci vyu¾ijte døíve definovaných funkcí queueEmpty,
** queueFront a queueRemove.
*/
	if (queueEmpty(q))
	{
		queueError(QERR_GET);
		return;
	}
	queueFront(q, c);	/* c bude ukazova» na prvý znak fronty */
	queueRemove(q);		/* Index prvého prvku sa posunie na nasledujúci */
}
void queueDump(void)
{
	int i,end=tail-1;

	if(queueEmpty())
		return;	
	
	end=(end<0)?(end+=N):end;
	
	i=head;
	while(i!=end){
		printf("%c ",array[i]);
		i++;
		i%=N;
	}
	printf("%c ",array[i]);
}
Beispiel #25
0
void queueGet (tQueue* q, char* c) {
/*
** Odstran znak ze zatku fronty a vrt ho prostednictvm parametru c.
** Pokud je fronta przdn, oetete to volnm funkce queueError(QERR_GET).
**
** Pi implementaci vyuijte dve definovanch funkc queueEmpty,
** queueFront a queueRemove.
*/
    if(queueEmpty(q) == 0)
    {
        queueFront(q, c);
        queueRemove(q);
    }
    else
    {
        queueError(QERR_GET);
    }
}
Beispiel #26
0
void queueGet (tQueue* q, char* c) {
/*
** Odstraní znak ze zaèátku fronty a vrátí ho prostøednictvím parametru c.
** Pokud je fronta prázdná, o¹etøete to voláním funkce queueError(QERR_GET).
**
** Pøi implementaci vyu¾ijte døíve definovaných funkcí queueEmpty,
** queueFront a queueRemove.
*/
	if(queueEmpty(q) == 0) //fronta nie je prazdna
	{
		queueFront(q, c); //najprv vratime znak
		queueRemove(q); //potom odstranime
	}
	else //fronta je prazdna
	{
		queueError(QERR_GET);
	}
}
Beispiel #27
0
void queueFront (const tQueue* q, char* c) {
/*
** Prostøednictvím parametru c crátí znak ze zaèátku fronty q.
** Pokud je fronta prázdná, o¹etøete to voláním funkce queueError(QERR_FRONT).
** Volání této funkce pøi prázdné frontì je v¾dy nutné pova¾ovat za nekorektní.
** Bývá to toti¾ dùsledek ¹patného návrhu algoritmu, ve kterém je fronta
** pou¾ita. O takové situaci se proto musí programátor-vývojáø dozvìdìt.
** V opaèném pøípadì je ladìní programù obtí¾nìj¹í!
**
** Pøi implementaci vyu¾ijte døíve definované funkce queueEmpty.
*/

    if(queueEmpty(q)){              // Zkontroluj, zda-li neni fronte prazdna
        queueError(QERR_FRONT);     // Vyhod chybovou hlasku
        return;                     // Ukonci
    }
    *c = q->arr[q->f_index];        // Vrat znak zacatku fronty
}
Beispiel #28
0
void queueFront (const tQueue* q, char* c) {
/*
** Prostøednictvím parametru c crátí znak ze zaèátku fronty q.
** Pokud je fronta prázdná, o¹etøete to voláním funkce queueError(QERR_FRONT).
** Volání této funkce pøi prázdné frontì je v¾dy nutné pova¾ovat za nekorektní.
** Bývá to toti¾ dùsledek ¹patného návrhu algoritmu, ve kterém je fronta
** pou¾ita. O takové situaci se proto musí programátor-vývojáø dozvìdìt.
** V opaèném pøípadì je ladìní programù obtí¾nìj¹í!
**
** Pøi implementaci vyu¾ijte døíve definované funkce queueEmpty.
*/
	if (queueEmpty(q))
	{
		queueError(QERR_FRONT);
		return;
	}
	*c = q->arr[q->f_index];	/* Na adresu kam ukazuje pointer c ulo¾í prvý prvok fronty */
}
Beispiel #29
0
/*----------------------------------------------------------------------------*/
static size_t canWrite(void *object, const void *buffer, size_t length)
{
  assert(length % sizeof(struct CanStandardMessage) == 0);

  struct Can * const interface = object;

  if (interface->mode == MODE_LISTENER)
    return 0;

  LPC_CAN_Type * const reg = interface->base.reg;
  const struct CanStandardMessage *input = buffer;
  const size_t initialLength = length;

  const irqState state = irqSave();

  if (queueEmpty(&interface->txQueue))
  {
    uint32_t status = reg->SR;

    while (length && (status & SR_TBS_MASK))
    {
      /* One of transmit buffers is empty */
      status = sendMessage(interface, (const struct CanMessage *)input, status);

      length -= sizeof(*input);
      ++input;
    }
  }

  while (length && !queueFull(&interface->txQueue))
  {
    struct CanMessage *output;

    queuePop(&interface->pool, &output);
    memcpy(output, input, sizeof(*input));
    queuePush(&interface->txQueue, &output);
    length -= sizeof(*input);
    ++input;
  }

  irqRestore(state);

  return initialLength - length;
}
Beispiel #30
0
//处理客户离开事件
void customerDeparture()
{
  int i = en.nType;

  deQueue(q[i], customer);

  totalTime += en.occurTime - customer.arrivalTime;    //累计客户逗留时间

  //设定第i队列的一个离开事件并插入事件表
  if(queueEmpty(q[i]))
  {
      Event tmpEn;
      tmpEn.occurTime = en.occurTime + customer.duration;
      tmpEn.nType = i;
      getHead(q[i], customer);
      orderInsert(ev, en, cmp);
  }

}