Пример #1
0
void UserAgent::cleanup(void) {
	common->isConnected=0;
	common->isRinging=0;
	common->rtpMgr->close();
	sipPackSend->toName=NULL;
	sipPackSend->toUri.id=NULL;
	sipPackSend->toUri.host=NULL;
	sipPackSend->callId = 0;
	callId=0;
	if((callIdHost) && (localHost!=callIdHost))
		free(callIdHost);
	if(remoteHost)
		free(remoteHost);
	if(remoteId)
		free(remoteId);
	remoteHost=NULL;
	remoteId=NULL;

	emptyQueue(common->sendQ,common->rmg);
	emptyQueue(common->codecQ,common->rmg);
	emptyQueue(common->playQ,common->rmg);

	sipPackSend->cSeqCode = 0;
	sipPackSend->cSeqMethod = NULL;
	state = SIP_UA_DISCONNECTED;
	defaultAction= SIP_NONE;
}
Пример #2
0
int main(int argc, char *argv[]) {
    printf("Creating queue... ");
    Queue q = emptyQueue();
    assert(q != NULL);
    printf("OK\n");

    printf("Checking if queue is empty... ");
    assert(isQueueEmpty(q));
    printf("OK\n");

    printf("Adding 1..%d to queue... ", TEST1);
    int i;
    for (i = 1; i <= TEST1; i++) {
        queue(q, i);
        assert(!isEmpty(q->s1) || !isEmpty(q->s2));
    }
    printf("OK\n");

    printf("Removing 1..%d from queue... ", TEST1);
    for (i = 1; i <= TEST1; i++) {
        assert(dequeue(q) == i);
    }
    printf("OK\n");

    printf("Checking if queue is empty... ");
    assert(isQueueEmpty(q));
    printf("OK\n");

    printf("All tests passed. You are awesome!\n");

    return EXIT_SUCCESS;
}
Пример #3
0
void bfs_traverse(double road[][MAX_POINT])
{
	int visited[MAX_POINT];
	int i;
	for (i = 1; i < MAX_POINT; i++)
		visited[i] = 0;
	struct queueLK *hq;
	initQueue(hq);
	for (i = 1; i < MAX_POINT; i++) {
		if (!visited[i]) {
			visited[i] = 1;
			visit(road, i);
			enQueue(hq, i);
			while (!emptyQueue(hq)) {
				int u = outQueue(hq);
				int j;
				for (j = 1; j < MAX_POINT; j++) {
					if (road[u][j] > 0.0001 && !visited[j]) {
						visited[j] = 1;
						visit(road, j);
						enQueue(hq, j);
					}
				}
			}
		}
	}
	clearQueue(hq);
}
Пример #4
0
unsigned short dequeue(unsigned char *p,unsigned size){

    	unsigned real;
    	unsigned datasize;

		if(emptyQueue())
		{
	    	        memset(p,0,size);
			return size;
		}

		pthread_mutex_lock(&sound_mutex);

		datasize = head > tail ? head - tail : (TAM - tail) + head ;
		
                pthread_mutex_unlock(&sound_mutex);

                real = datasize > size ? size : datasize;

		if(tail + real < TAM)
		{
			memcpy(p,ptr_buf+tail,real);
			tail+=real;
		}
		else
		{
			memcpy(p,ptr_buf + tail, TAM - tail);
			memcpy(p+ (TAM-tail),ptr_buf , real - (TAM-tail));
			tail = (tail + real) - TAM;
		}

        return real;
}
Пример #5
0
void NetworkWidget::checkNetwork()
{
    // check if we have received any packets since last time.

    if (stats_packets == 0 || stats_packets > stats_packets_old) {
        // Restart the Timer
        NetworkTimer->stop();
        NetworkTimer->start( networkFailureTime );

        stats_packets_old = stats_packets; // Update the value
        return;
    }

    if (stats_packets == stats_packets_old) {
        // Network timeout has occured.
        STATE = NET_FAILURE;
        stats_network_failures++;
        ui->lblStatus->setText("Network Failure!");        
        ui->lblNetworkFailures->setText(QString::number(stats_network_failures, 10));

        NetworkTimer->stop();
        // Dump queue
        emptyQueue();

        if (ui->chkDefaultsOnNetworkFail->isChecked()) {
            sendDefaults();
        }
    }
}
Пример #6
0
void testQueue()
{
	pushQueue("we");
	pushQueue("are");
	pushQueue("the");
	pushQueue("champion");
	pushQueue("!");

	while (!emptyQueue())
	{
		showQueue();
		printf("Pop the front of queue: %s\n", frontQueue()->value);
		popQueue();
	}

	pushQueue("we");
	pushQueue("are");
	pushQueue("the");
	pushQueue("champion");
	pushQueue("!");

	showQueue();
	clearQueue();
	printf("After clearing:\n");
	showQueue();
	
	return;
}
Пример #7
0
int main(int argc, char* argv[]) {
    Queue* q = newQueue(5);

    enqueue(q, 1);
    enqueue(q, 2);
    enqueue(q, 3);

    printf("%d\n", dequeue(q));
    printf("%d\n", dequeue(q));

    enqueue(q, 4);
    enqueue(q, 5);
    enqueue(q, 6);

    printf("%d\n", dequeue(q));
    printf("%d\n", dequeue(q));
    printf("%d\n", dequeue(q));
    printf("%d\n", dequeue(q));

    printf("Empty: %d\n", emptyQueue(q));

    deleteQueue(q);

    return 0;
}
Пример #8
0
NetworkWidget::NetworkWidget(QWidget *parent, AbstractSerial *serial) :
    QWidget(parent),
    serial(serial),
    ui(new Ui::NetworkWidget)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    connect(udpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));

    if ( udpSocket->localAddress().isNull() ) {
        ui->lblIP_address->setText("0.0.0.0");
    } else {
        ui->lblIP_address->setText( udpSocket->localAddress().toString() );
    }

    QLineEdit *temp[] = { ui->PWM_01, ui->PWM_02, ui->PWM_03, ui->PWM_04, ui->PWM_05, ui->PWM_06, ui->PWM_07, ui->PWM_08, ui->PWM_09, ui->PWM_10, ui->PWM_11, ui->PWM_12 };
    for (unsigned char i=0; i<(sizeof(temp)/sizeof(temp[0])); i++)
        currentServoValue[i] = temp[i];

    // Zero out all the stats.
    stats_packets = stats_invalid = stats_queue_max = stats_discarded = stats_packets_old = stats_network_failures = 0;
    ui->lblStatus->setText(tr("Not Listening"));

    socketOpen = false;
    STATE = NOT_LISTENING;
    emptyQueue();

    ui->btnClearEmergencyStop->setDisabled(true);

    OutputTimer = new QTimer(this);
    NetworkTimer = new QTimer(this);
    connect(OutputTimer, SIGNAL(timeout()), this, SLOT(ouputServoData()));
    connect(NetworkTimer, SIGNAL(timeout()), this, SLOT(checkNetwork()));
}
Пример #9
0
unsigned short dequeue(unsigned char *p,unsigned size){

    	unsigned real;

		if(emptyQueue())
		{
	    	memset(p,0,size);//TODO ver si quito para que no petardee
			return size;
		}

		pthread_mutex_lock(&mut);

		unsigned datasize = head > tail ? head - tail : (TAM - tail) + head ;
		real = datasize > size ? size : datasize;

		if(tail + real < TAM)
		{
			memcpy(p,ptr_buf+tail,real);
			tail+=real;
		}
		else
		{
			memcpy(p,ptr_buf + tail, TAM - tail);
			memcpy(p+ (TAM-tail),ptr_buf , real - (TAM-tail));
			tail = (tail + real) - TAM;
		}

		pthread_mutex_unlock(&mut);

        return real;
}
Пример #10
0
static void _traverseBFT (BSTNODE* root, void (*process) (PACKAGE* package) )
{
	BSTNODE* currentNode;
	BSTNODE* tempNode;
	QUEUE* queue;

	queue = createQueue();
	if(!queue)
	{
		printf("\nMemory Overflow!\n");
		exit(201);
	}
	currentNode = root;

	while(currentNode != NULL)
	{
		process ( currentNode->ptrPackage );
		if(currentNode->left != NULL)
			enqueue(queue, currentNode->left);
		if(currentNode->right != NULL)
			enqueue(queue, currentNode->right);
		if(!emptyQueue(queue))
		{
			dequeue(queue, (void**)&tempNode);
			currentNode = tempNode;
		}
		else currentNode = NULL;
	}
	queue = destroyQueue(queue);
	return;

}// _traverseBFT
Пример #11
0
int main(int argc, char **argv)
{
	int N = (argc < 2) ? 20 : atoi(argv[1]);
	if (N < 20) N = 20;
	Queue q;
	q = newQueue();
	int i;
	char x[50];
	for (i = 0; i < N; i++) {
		if (random()%10 > 5) {
			if (!emptyQueue(q)) {
				char *str = leaveQueue(q);
				printf("Remove %s\n",str);
				free(str);
			}
		}
		else {
			randomString(x);
			enterQueue(q,x);
			printf("Insert %s\n",x);
		}
		showQueue(q);
	}
	disposeQueue(q);
	return 0;
}
Пример #12
0
int deQueue(Queue *q, int *val) {
    if (emptyQueue(q)) {
        return 0 ;//empty can not return
    } else {
        *val = q->queue[q->front] ;
        q->front = (q->front+1)%NUM ;
        return 1 ;
    }
}
Пример #13
0
int main()
{
    // Initialize hardware
    if (!elev_init()) {
        printf(__FILE__ ": Unable to initialize elevator hardware\n");
        return 1;
    }
    printf("Best Elevator Software,  version: 2.27.14\n" );
    initialize();
    lastFloorReached = N_FLOORS+1;
    while (1) {
        queueIsEmpty = emptyQueue();
        obstructionSignal = elev_get_obstruction_signal();
        stoppedSignal = elev_get_stop_signal();
        thisFloor = elev_get_floor_sensor_signal();
        duration = clock()-start;

        if ( timerActive && duration > seconds ) {
            timerActive = 0;
            duration = 0;
            stateMachine( TIMEROUT );
        }

        if ( obstructionSignal != lastObstructionSignal ) {
            if ( obstructionSignal == 1 )
                stateMachine( OBSTRON );
            if ( obstructionSignal == 0 )
                stateMachine( OBSTROFF );
            lastObstructionSignal = obstructionSignal;
        }

        if ( stoppedSignal != lastStoppedSignal ) {
            if ( stoppedSignal == 1 )
                stateMachine( STOP );
            lastStoppedSignal = stoppedSignal;
        }

        if ( thisFloor != -1 && ( lastFloorReached != thisFloor ) ) {
            if ( thisFloor-lastFloorReached < 0 )
                direction = DOWN;
            if ( thisFloor-lastFloorReached > 0 )
                direction = UP;
            lastFloorReached = thisFloor;
            elev_set_floor_indicator( thisFloor );
        }

        if ( order() && directionToGo( thisFloor, getNextOrder( thisFloor ) ) == 0 )
            stateMachine( NEWORDERCURRENTFLOOR );

        if ( thisFloor != -1 && directionToGo( thisFloor , getNextOrder( thisFloor ) ) == 0 && !timerActive )
            stateMachine( FLOORREACHED );

        if( queueIsEmpty == 1 && order() )
            stateMachine( NEWORDEREMPTYQUEUE );
    }
    return 0;
}
Пример #14
0
/*
    Get the datagrams and store them in a queue.
    We have a QTimer that is running and taking them out of the queue.
*/
void NetworkWidget::processPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size());

        if (STATE == EMERG_STOP || (STATE == NET_FAILURE && ui->chkStopOnNetworkFailure->isChecked())) {
            // Discard all packets
            return;
        }

        // STOP CONDITION
        if ( datagram.size() && datagram[0]==(char)0 ) {
            STATE = EMERG_STOP;

            // output whatever is need for stop.
            sendDefaults();

            // Stop the network timer
            NetworkTimer->stop();
            emptyQueue();

            ui->btnClearEmergencyStop->setEnabled(true);
            ui->lblEmergencyStatus->setText("EMERGENCY STOP!");
            QPalette red_text;
            red_text.setColor(QPalette::WindowText, Qt::red);
            ui->lblEmergencyStatus->setPalette(red_text);
            ui->lblEmergencyStatus->setFrameStyle(QFrame::Box);
            ui->lblStatus->setText("EMERGENCY STOP!");
            return;
        }

        // Increment the received packet count
        stats_packets++;

        // check if valid packet
        if (validPacket(datagram.constData())) {
            queue.enqueue(datagram);
        } else {
            stats_invalid++;
        }
    }

    // Update the Statistics
    ui->lblPackets->setText(QString::number(stats_packets,10));
    ui->lblInvalid->setText(QString::number(stats_invalid,10));

    // Check if a network failure occured.
    if (STATE == NET_FAILURE && !ui->chkStopOnNetworkFailure->isChecked()) {
        STATE = LISTENING;
        NetworkTimer->start( networkFailureTime );
    }
    ui->lblStatus->setText("Receiving Packets...");
}
bool JacobsLadder::hasPriority(MovementType type) {
  if (queue.isEmpty() || type == Timeout) {
    return true;
  }
  MovementType frontType = (MovementType) queue.peek().type;
  if (type < frontType) {
    return false;
  } else if (type > frontType) {
    emptyQueue();
  }
  return true;
}
Пример #16
0
///////////////////////////////////////////////////////////////
// rerun is to do a rerun
// Takes the elements of the queue, if there is no more 
// work it breaks, if it is a copy event is calculates the
// degree puts it in the node and makes sure the node has 
// a child, and if it is a run event it runs the wake up 
// code
/////////////////////////////////////////////////////////////
cluster* rerun(Queue *q,tree_t* tree, int doSynch)
{
  cluster* root;
  node *nd = NULL;
  int curheight = -1;
  deprintf(" \n Rerunning \n"); 
  
  currentTree  = tree;
  currentQueue = q;
 
  morework=1;
  //debug=1;
  while (!isEmpty(q)) {  
    // Loop
    // Free the qnode 
    drun(assert(!isEmpty(q)));
    nd = removeQueue(q);
    
    if(!(nd->deleted)) {    
      //If it is the end of a round then check if all is done, otherwise continue, resetting
      //the morework flag
      if(nd->height != curheight)
	{
	  curheight = nd->height;
	  deprintf("Height is %d\n",curheight);
	  if(morework == 0) break;
	  morework = 0;
	  }
      deprintf("Running %d\n",nd->nId);
      runNode(nd,q);
      drun(assert(verifyVertex(nd)));
      
    }
  }//while
  
  // Empty the queue
  emptyQueue(q);
  if(PUSHDOWN)
    {
    deprintf("push down\n");
    pushDownList(&oldRootList);
    }
  if(doSynch) {
     root = syncList(&newRootList);
  }
  
  return root; 
 
  
}
Пример #17
0
void* threaded_sound_play(void* args)
{
	unsigned char buf[TAM];

	while(1)
	{

		if(!emptyQueue())
		{
			short len = dequeue(&buf[0],TAM);
			__android_log_print(ANDROID_LOG_DEBUG, "MAME4all.so", "dequeue:%d ",len);
			//dumpSound_callback(buf,len);
		}
		else
			sched_yield();
	}
}
Пример #18
0
int Queue::dequeue() {
	int index;
	queueNode *tempPtr;
	if (emptyQueue()) {
		exit(EXIT_FAILURE);
	} else {
		tempPtr = front;
		index = front->index;
		front = front->prevPtr;
		if (front == nullptr) 
			rear = nullptr;
		else
			delete tempPtr;
		size--;
		return index;
	}
}
Пример #19
0
void Queue::enqueue(int index) {
	queueNode *tempPtr;
	tempPtr = new (queueNode);
	if (tempPtr != nullptr) {
		tempPtr->index = index;
		tempPtr->prevPtr = nullptr;
		if (emptyQueue()) {
			front=rear=tempPtr;
		} else {
			rear->prevPtr = tempPtr;
			rear = tempPtr;
		}
		size++;
	} else {
		exit(EXIT_FAILURE); 
	}
}
Пример #20
0
int deQueue(struct ArrayQueue *Q)
{
    int data=-1;
    if(emptyQueue(Q))
    {
        printf("Queue is empty");
        return -1;
    }
    else
    {
        data=Q->array[Q->front];
        if(Q->front==Q->rear)
            Q->front=Q->rear=-1;
        else
            Q->front=(Q->front+1)%Q->capacity;
    }
    return data;
}
Пример #21
0
std::vector<std::shared_ptr<Task> > WSCoreBoundPriorityQueue::stopQueue() {
  if (_status != STOPPED) {
    // the thread to be stopped is either executing a task, or waits for the condition variable
    // set status to "TO_STOP" so that the thread either quits after executing the task, or after having been notified by the condition variable
    // we need the mutex here, otherwise, we might call notify prior to the thread going to sleep
    {
      std::lock_guard<lock_t> lk(_queueMutex);
      _status = TO_STOP;
      //wake up thread in case thread is sleeping
      _condition.notify_one();
    }
    _thread->join();
    delete _thread;
    _thread = nullptr;
    _status = STOPPED;
  }
  return emptyQueue();
}
Пример #22
0
/**
 * Input: - queue of checks; - vector of two ints to return some info
 * Cycles through the queue of checks and deletes it (frees all the memory).
 * While doing that it counts the number of checks in the queue (nch) and 
 * the total amount they add up to (vch) and stores them in the vector given, 
 * respectively.
 */
void count_clearQueueCheck(Queue q, long int vec[2]){
  int nch = 0, vch = 0;
  CheckP check;

  /* get and delete all the nodes (checks) of the queue one at a time, while 
   * getting their information (to update the nch and vch) and freeing the 
  * memory allocated for them */
  while(!emptyQueue(q)){
    check = (CheckP) getFirstQueue(q);

    nch++;
    vch += getCheckVAL(check);

    freeCheck(check);
  }
 /* storing the nch and vch in the vector */
  vec[0] = nch;
  vec[1] = vch;
}
Пример #23
0
void FloorGenerator::resetMap()
{
	shutdown();

	map = new unsigned char* [LIMIT];

	for(int i = 0; i < LIMIT; i++)
		map[i] = new unsigned char[LIMIT];

	for(int i = 0; i < LIMIT; i++)
	{
		for(int j = 0; j < LIMIT; j++)
			map[i][j] = ' ';
	}

	emptyCor();
	emptyRoom();
	emptyQueue();
}
// Note: Level order cannot be done recursively
void levelOrder(Link n)
{
	Queue q = newQueue();
	Link curNode = NULL;
	enQueue(q, n);
	while ( !emptyQueue(q) ){
		curNode = deQueue(q);
		if (curNode->left != NULL){
			enQueue(q, curNode->left);
		}

		if (curNode->right != NULL){
			enQueue(q, curNode->right);
		}
		printf("%d ", curNode->value);
	} 
	printf("\n");
	deleteQueue(q);
}
Пример #25
0
/*! This method sends a single string directly to the server. To make sure
    this message arrives, the time of one complete cycle is waited before and
    after the message is sent.
    \param str string that should be sent to the server
    \return true when message was sent, false otherwise */
bool ActHandler::sendMessage( char * str )
{
  emptyQueue( );
#ifdef WIN32
  Sleep( SS->getSimulatorStep() );
#else
  poll( 0, 0, SS->getSimulatorStep() );
#endif

  bool bReturn = connection->sendMessage( str );
  Log.logFromSignal( 2, " send message to server and wait: %s", str);

#ifdef WIN32
  Sleep( SS->getSimulatorStep() );
#else
  poll( 0, 0, SS->getSimulatorStep() );
#endif
  return bReturn;
}
Пример #26
0
void enqueue(QUEUE **head, QUEUE **last, char *value) {
    QUEUE *buffer;
    buffer = malloc(sizeof (QUEUE));

    if (buffer != NULL) {
        buffer->value = (char*) malloc(sizeof (char) * strlen(value));
        memcpy(buffer->value, value, strlen(value) + 1);
        buffer->link = NULL;

        if (emptyQueue((*head))) {
            *head = buffer;
        } else {
            (*last)->link = buffer;
        }
        (*last) = buffer;
    } else {
        fputs("Not enough memory.", stdout);
        abort();
    }
}
WSCoreBoundTaskQueue::run_queue_t WSCoreBoundTaskQueue::stopQueue() {
  if (_status != STOPPED) {
    // the thread to be stopped is either executing a task, or waits for the condition variable
    // set status to "TO_STOP" so that the thread either quits after executing the task, or after having been notified by the condition variable
    {
      std::lock_guard<std::mutex> lk(_queueMutex);
      {
        std::lock_guard<std::mutex> lk(_threadStatusMutex);
        _status = TO_STOP;
      }
      //wake up thread in case thread is sleeping
      _condition.notify_one();
    }
    _thread->join();
    delete _thread;
    _thread = NULL;
    _status = STOPPED;
  }
  return emptyQueue();
}
Пример #28
0
void NetworkWidget::on_btnClearEmergencyStop_clicked()
{
    if (STATE != EMERG_STOP) {
        return;
    }

    QString status;

    STATE = LISTENING;
    QPalette black_text;
    black_text.setColor(QPalette::WindowText, Qt::black);
    ui->lblEmergencyStatus->setPalette(black_text);
    ui->lblEmergencyStatus->setFrameStyle(QFrame::Plain);
    ui->lblEmergencyStatus->setText("Status: OK");

    status = "Listening on " + udpSocket->localAddress().toString() + ":" + QString::number(portNum, 10);
    ui->lblStatus->setText(status);
    emptyQueue();
    NetworkTimer->stop();
    OutputTimer->start( outputTime );
}
Пример #29
0
std::vector<std::shared_ptr<Task> > CoreBoundQueue::stopQueue() {
  if (_status != STOPPED) {
    // the thread to be stopped is either executing a task, or waits for the condition variable
    // set status to "TO_STOP" so that the thread either quits after executing the task, or after having been notified by the condition variable
    {
      std::lock_guard<lock_t> lk(_queueMutex);
      {
        std::lock_guard<lock_t> lk(_threadStatusMutex);
        _status = TO_STOP;
      }
      //wake up thread in case thread is sleeping
      _condition.notify_one();
    }
    _thread->join();
    delete _thread;
    //just to make sure it points to nullptr
    _thread = nullptr;

    _status = STOPPED;

  }
  return emptyQueue();
}
Пример #30
0
static void run_bfs(Graph* g, int start, TraverseListener* listener, int* discovered, int* processed) {
    Queue* q = newQueue(g->nvertices);
    enqueue(q, start);
    discovered[start] = 1;

    while (!emptyQueue(q)) {
        int v = dequeue(q);
        if (listener->beforeProcess != NULL) {
            listener->beforeProcess(v);
        }

        Node* node = g->nodes[v];
        while (node != NULL) {
            int y = node->label;
            if (!discovered[y]) {
                enqueue(q, y);
                discovered[y] = 1;
                if (listener->onDiscovered != NULL) {
                    listener->onDiscovered(y, v);
                }
            } 
            if (!processed[y] || g->directed) {
                if (listener->onProcessEdge != NULL) {
                    listener->onProcessEdge(v, y);
                }
            }

            node = node->next;
        }

        processed[v] = 1;
        if (listener->afterProcess != NULL) {
            listener->afterProcess(v);
        }
    }
}