// Обрабатываем событие void *worker(void *args) { // Получаем аргументы в новом потоке struct WorkerArgs *workerArgs = args; while (!done) { // Ожидание поступления события в очередь pthread_mutex_lock(workerArgs->mutex); while (isEmptyQueue(workerArgs->queue)) { pthread_cond_wait(workerArgs->condition, workerArgs->mutex); } struct epoll_event event; popQueue(workerArgs->queue, &event); pthread_mutex_unlock(workerArgs->mutex); if (event.data.fd == socketfd) { int connectionfd = acceptConnection(); if (connectionfd == -1) { fprintf(stderr, "Error: accepting new connection\n"); continue; } if (handleEvent(connectionfd) == -1) { fprintf(stderr, "Error: handling event\n"); continue; } } else { if (handleEvent(event.data.fd) == -1) { fprintf(stderr, "Error: handling event\n"); continue; } } } return NULL; }
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; }
int MyThreadJoin(MyThread thread) { UThread* childthread = (UThread *)thread; bool flag = false; UThread* temp = currThreadNode->child; while (temp != NULL) { if (temp == thread) { flag = true; temp->JoinPresent = 1; break; } else temp = temp->sib; } if (!flag) return -1; else { UThread* tempnode = currThreadNode; pushToBQueue(currThreadNode); popQueue(); if(currThreadNode != NULL) swapcontext(tempnode->ctx, currThreadNode->ctx); return 0; } }
//-------------------------------------------------------------- void goThreadedVideo::psuedoUpdate() { if(!isThreadRunning() && loaded[cueVideo] && !textured[cueVideo]) { // setup the videos texture and force the // first frame of the texture to upload // (this required changes to ofVideoPlayer, see goVideoPlayer) video[cueVideo]->forceTextureUpload(); video[cueVideo]->setUseTexture(true); // unless it's the very fist load, lets pause the current video if(!firstLoad) { video[currentVideo]->setPaused(true); } else firstLoad = false; // force an update of the cue'd videos frame //video[cueVideo]->update(); // update texture flags and set swapVideo flag to do a // "flickerless" change between cue and current video[] players textured[cueVideo] = true; swapVideo = true; } #ifdef USE_QUE if(!loading) popQueue(); #endif }
int main(int argc, char const *argv[]) { struct queue q; //Create 1 queue initQueue(&q); //Init pointers/attirbutes pushQueue(&q,1); //Push 1 pushQueue(&q,2); //Push 2 pushQueue(&q,3); //Push 3 int popValue = popQueue(&q); //Set popValue = to most first element (most recent) while(popValue != -1) //While element exists { printf("%d\n", popValue); //print to screen popValue = popQueue(&q); //Move to next pop value } return 0; }
void MyThreadExit(void) { bool flag = false; UThread* parentthread = currThreadNode->parent; UThread* currChild = currThreadNode->child; if (parentthread != NULL) { UThread* temp = parentthread->child; while (temp != NULL) { if (temp->JoinPresent == 1 && temp != currThreadNode) { flag = true; break; } temp = temp->sib; } if ((!flag) && (currThreadNode->JoinPresent == 1)) { delQueue(parentthread); } if (parentthread->child == currThreadNode) { parentthread->child = currThreadNode->sib; } else { UThread* temp2 = parentthread->child; while (temp2->sib != currThreadNode) { temp2 = temp2->sib; } temp2->sib = temp2->sib->sib; } currThreadNode->parent = NULL; } while (currChild != NULL) { currChild->parent = NULL; currChild = currChild->sib; } UThread* temp3 = currThreadNode; popQueue(); if (currThreadNode != NULL) { free(temp3->ctx); free(temp3); setcontext(currThreadNode->ctx); } }
struct pcbHeader* createProcess(void (*func)(), int stack) { void *memPtr = (void *) kmalloc(stack); // the memory pointer should not be null struct pcbHeader * pcb = popQueue(&stoppedHead); if (memPtr == NULL || pcb == NULL) { return NULL; } //prevent runnig of the end of the process table //kprintf("CREATE: allocating memory at %x,stack size = %d, pcbaddress = %x\n", memPtr, stack, pcb); struct contextFrame *ctx = (long)memPtr + stack - SAFETY_MARGIN - sizeof(struct contextFrame); //Initialize pcb Header //find a pcb spot //Assign the pid and increment pcb->pid = pidCounter++; //limite the pid values if(pidCounter > 10000) { pidCounter = 2; } pcb->state = READY; pcb->memStart = memPtr; pcb->esp = ctx; pcb->next = NULL; pcb->ignoredSignals = 0xFFFFFFFF; pcb->handledSignals = 0x00000000; pcb->incomingSignals = 0x00000000; pcb->fdt[0]= NULL; pcb->fdt[1]= NULL; pcb->fdt[2]= NULL; pcb->fdt[3]= NULL; // Initialize context frame //Registers ctx->edi = 0; ctx->esi = 0; ctx->ebp = 0; ctx->esp = 0; ctx->ebx = 0; ctx->edx = 0; ctx->ecx = 0; ctx->eax = 0; //Instruction pointer ctx->iret_eip = func; // code segment ctx->iret_cs = getCS(); // status flags ctx->eflags = 0x00003200; //why doesn't this need a spot for EBP? ctx->retAdd = &sysstop; //put on the ready stack return pcb; }
void Player_listen(void *self) { Player *player = self; for(;;) { if (pthread_mutex_lock(&player->queue->queue_lock) != 0) { syslog(LOG_ERR,"Animationplayer: Can't get the lock on the queue."); } if (player->queue->current == NULL) { syslog(LOG_DEBUG,"Waiting..."); pthread_cond_wait(&player->queue->queue_not_empty, &player->queue->queue_lock); } syslog(LOG_DEBUG, "Working....."); Command *command = player->queue->current->command; if (command->action == play) { if (player->run == 1 && player->currentAnimation != NULL && player->currentAnimation->repeat == -1) { set_run_state(0); void* result; if (pthread_join(runner, &result) != 0) { syslog(LOG_ERR,"Animationplayer: failed to wait for current player thread."); } } if (player->run == 0) { set_run_state(1); spawnPlayer((Animation*) command->value); popQueue(); } } if (command->action == stop || command->action == halt) { syslog(LOG_ERR,"Animationplayer: halting current animation %s.", player->currentAnimation->name); set_run_state(0); void* result; if (pthread_join(runner, &result) != 0) { syslog(LOG_ERR,"Animationplayer: failed to wait for current player thread."); } popQueue(); } if (pthread_mutex_unlock(&player->queue->queue_lock) != 0) { syslog(LOG_ERR,"Animationplayer: Can't release the lock on the queue."); } } }
void grant(struct Position* _p, struct Node* _t) { struct QueueElem* x = popQueue(&_p->removedGrantees); if (x == NULL) { addToQueue(&_p->lockGrantees, _t); } else { addElemToQueue(&_p->lockGrantees, x, _t); } }
void completer (AcTrie acTrie) { // File Queue q = NULL; // Liste des transitions depuis la racine (longueur de l = alphaSize) int * l = acTrie->trie->transition[0]; /* Remplissage de la file avec les premiers noeuds suivant la racine * + ajout des suppléants (les suppléants des successeurs de la racine * sont la racine elle même) */ for (int i = 0; i < alphaSize; i++) { // On ne prend pas en compte les transitions du type (0, i, 0) if (l[(int) alpha[i]] != 0 && l[(int) alpha[i]] != -1) { q = pushQueue (q, l[(int) alpha[i]]); acTrie->sup[l[(int) alpha[i]]] = 0; } } // Ajout des suppléants des tous les autres états while (q != NULL) { // On prend le noeud en tête de file int h = topQueue (q); q = popQueue(q); // Ainsi que ses successeurs l = acTrie->trie->transition[h]; // Pour chacunes de ses transitions for (int i = 0; i < alphaSize; i++) { int p = l[(int) alpha[i]]; if (p != -1) { // On enfile les successeurs q = pushQueue (q, p); // On prend le suppléants du noeud actuel int s = acTrie->sup[h]; // Recherche du suppléant while (acTrie->trie->transition[s][(int) alpha[i]] == -1) { s = acTrie->sup[s]; //printf("**\n"); } // Affectation du suppléant acTrie->sup[p] = acTrie->trie->transition[s][(int) alpha[i]]; // sortie(0) <- sortie(0) U sortie(sup(p)) if (acTrie->sortie[acTrie->sup[p]] == 1) { acTrie->sortie[p] = 1; } } } } }
void MyThreadYield(void) { if(rdyhead == NULL) return; UThread* tempnode = currThreadNode; pushToRQueue(currThreadNode); popQueue(); if(currThreadNode != NULL) swapcontext(tempnode->ctx, currThreadNode->ctx); return; }
/* Create a Huffman Tree */ queue *createHuffmanTree(queue *head){ queue *aux1, *aux2; while(head->next){ /* Pop two elements out of the queue */ aux1 = popQueue(&head); aux2 = popQueue(&head); queue *combined = (queue*)malloc(sizeof(queue)); /* Create combined node */ if(aux1->value.frequency <= aux2->value.frequency){ combined->left = aux1; combined->right = aux2; } else{ combined->left = aux2; combined->right = aux1; } /* New node frequency is the sum of the combined nodes */ combined->value.frequency = aux1->value.frequency + aux2->value.frequency; /* Push back into queue */ pushQueueNode(&head, combined); } return head; }
void Ngrams::addToken ( const string & token ) { int count = pushQueue( token.c_str() ); if ( count == this->ngramN ) { parse(); popQueue(); } else if ( count == this->ngramN - 1 ) { preParse( count ); } }
ssize_t Console_APPIO_Write(int fd, const void *buf, size_t count) { struct QPacket pkt; pkt.data.cbuf = buf; pkt.sz = count; //Pop the most recent if the queue is full if (writeQueue.numElem >= writeQueue.elemArrSz) { popQueue(&writeQueue); } pushQueue(&writeQueue, pkt); return count; }
void popQThread(struct queue* localQ) { sleep(10); //Setting this because it gives the other thread a "head start". Usually, we'd implement a //check to see if the other thread has begun or not, then start based on that condition QUEUE_DATATYPE* popPtr = NULL; while(fillThreadRunning || localQ->count > 0) { while(queueIsProcessing) {} //While other routine is processing, just chill, as soon as it's done, jump in queueIsProcessing = true; //Lock for me popPtr = popQueue(localQ); //Set pop pointer if(popPtr != NULL) putchar(*popPtr); //if pointer is not NULL, print value at pointer queueIsProcessing = false; //Release } pthread_exit(NULL); }
void MySemaphoreWait(MySemaphore sem) { USemaphore *tempsem = (USemaphore*)sem; if(tempsem ->val > 0) { tempsem->val--; } else{ pushToSemQueue(tempsem, currThreadNode); UThread* tempthread = currThreadNode; popQueue(); if (currThreadNode != NULL) { swapcontext(tempthread->ctx, currThreadNode->ctx); } } }
void MyThreadJoinAll(void) { UThread* temp = currThreadNode->child; if(temp == NULL) return; while (temp != NULL) { temp->JoinPresent = 1; temp = temp->sib; } UThread* tempNode = currThreadNode; pushToBQueue(currThreadNode); popQueue(); if (currThreadNode != NULL) { swapcontext(tempNode->ctx, currThreadNode->ctx); } }
void Console_APPIO_Tasks (SYS_MODULE_OBJ object) { /* Update the application state machine based * on the current state */ struct QPacket pkt; size_t *sizeRead; switch(consAppIOData.state) { case CONSOLE_APPIO_STATE_INIT: /* Initialize APPIO */ DBINIT(); consAppIOData.state = CONSOLE_APPIO_STATE_READY; break; case CONSOLE_APPIO_STATE_START_READ: if (readQueue.numElem) { pkt = rdQueueElements[readQueue.tailPos]; DBGETS (pkt.data.buf, 128); if (*(char*)pkt.data.buf != '\0') { rdQueueElements[readQueue.tailPos].sz = strlen((char*)pkt.data.buf); consAppIOData.state = CONSOLE_APPIO_STATE_READ_COMPLETE; } } break; case CONSOLE_APPIO_STATE_READ_COMPLETE: sizeRead = &rdQueueElements[readQueue.tailPos].sz; popQueue(&readQueue); if (readQueue.numElem == 0) { if (consAppIOData.rdCallback != NULL) { consAppIOData.rdCallback(sizeRead); } consAppIOData.state = CONSOLE_APPIO_STATE_READY; } else { consAppIOData.state = CONSOLE_APPIO_STATE_START_READ; } break; case CONSOLE_APPIO_STATE_READY: if (writeQueue.numElem) { consAppIOData.state = CONSOLE_APPIO_STATE_START_WRITE; } else if (readQueue.numElem) { consAppIOData.state = CONSOLE_APPIO_STATE_START_READ; } break; case CONSOLE_APPIO_STATE_START_WRITE: if (writeQueue.numElem) { pkt = wrQueueElements[writeQueue.tailPos]; DBPRINTF("%s",(char*)pkt.data.buf); consAppIOData.writeCycleCount = 0; consAppIOData.state = CONSOLE_APPIO_STATE_WAIT_FOR_WRITE_COMPLETE; } break; case CONSOLE_APPIO_STATE_WAIT_FOR_WRITE_COMPLETE: pkt = wrQueueElements[writeQueue.tailPos]; /* Burn cycles to allow to printf to complete */ if(consAppIOData.writeCycleCount++ > pkt.sz * 400) { if (consAppIOData.wrCallback != NULL) { consAppIOData.wrCallback((void *)pkt.data.cbuf); } popQueue(&writeQueue); if (writeQueue.numElem == 0) { consAppIOData.state = CONSOLE_APPIO_STATE_READY; } else { consAppIOData.state = CONSOLE_APPIO_STATE_START_WRITE; } } break; case CONSOLE_APPIO_STATE_OPERATIONAL_ERROR: /* We arrive at this state if the APPIO driver reports an error on a read or write operation We will attempt to recover by flushing the local buffers */ Console_APPIO_Flush(); break; case CONSOLE_APPIO_STATE_CRITICAL_ERROR: break; default: break; } }
TCB *createThread( addr_t threadAddr, addr_t addrSpace, addr_t stack, TCB *exHandler ) { TCB * thread = NULL; pde_t pde; #if DEBUG if( exHandler == NULL ) kprintf("createThread(): NULL exception handler.\n"); #endif /* DEBUG */ if( threadAddr == NULL ) RET_MSG(NULL, "NULL thread addr") else if( addrSpace == NULL_PADDR ) RET_MSG(NULL, "NULL addrSpace") assert( (addrSpace & 0xFFFu) == 0u ); thread = popQueue(&freeThreadQueue); if( thread == NULL ) RET_MSG(NULL, "Couldn't get a free thread.") assert( thread->threadState == DEAD ); thread->priority = NORMAL_PRIORITY; thread->cr3.base = (addrSpace >> 12); thread->cr3.pwt = 1; thread->exHandler = exHandler; thread->waitThread = NULL; thread->threadQueue.tail = thread->threadQueue.head = NULL; thread->queueNext = thread->queuePrev = thread->timerNext = NULL; thread->timerDelta = 0u; thread->sig_handler = NULL; assert( (u32)addrSpace == ((u32)addrSpace & ~0xFFFu) ); // Map the page directory into the address space *(u32 *)&pde = (u32)addrSpace | PAGING_PWT | PAGING_RW | PAGING_PRES; writePDE( PAGETAB, &pde, addrSpace ); // Map the kernel into the address space readPDE( KERNEL_VSTART, &pde, (getCR3() & ~0xFFFu) ); writePDE( KERNEL_VSTART, &pde, addrSpace ); #if DEBUG readPDE( 0x00, &pde, (getCR3() & ~0xFFFu) ); writePDE( 0x00, &pde, addrSpace ); #endif /* DEBUG */ memset(&thread->execState.user, 0, sizeof thread->execState.user); thread->execState.user.eflags = 0x0201u; //0x3201u; // XXX: Warning: Magic Number thread->execState.user.eip = ( dword ) threadAddr; /* XXX: This doesn't yet initialize a kernel thread other than the idle thread. */ if( GET_TID(thread) == IDLE_TID ) { thread->execState.user.cs = KCODE; thread->execState.user.ds = thread->execState.user.es = KDATA; thread->execState.user.esp = stack - (sizeof(ExecutionState)-8); memcpy( (void *)thread->execState.user.esp, (void *)&thread->execState, sizeof(ExecutionState) - 8); } else if( ((unsigned int)threadAddr & KERNEL_VSTART) != KERNEL_VSTART ) { thread->execState.user.cs = UCODE; thread->execState.user.ds = thread->execState.user.es = thread->execState.user.userSS = UDATA; thread->execState.user.userEsp = stack; } thread->threadState = PAUSED; return thread; }
int releaseThread( TCB *thread ) { #if DEBUG TCB *retThread; #endif assert(thread->threadState != DEAD); if( thread->threadState == DEAD ) return -1; /* If the thread is a sender waiting for a recipient, remove the sender from the recipient's wait queue. If the thread is a receiver, clear its wait queue after waking all of the waiting threads. */ switch( thread->threadState ) { /* Assumes that a ready/running thread can't be on the timer queue. */ case READY: #if DEBUG retThread = #endif /* DEBUG */ detachQueue( &runQueues[thread->priority], thread ); assert( retThread == thread ); break; case WAIT_FOR_RECV: case WAIT_FOR_SEND: case SLEEPING: #if DEBUG retThread = #endif /* DEBUG */ timerDetach( thread ); assert( retThread == thread ); break; } /* XXX: Are these implemented properly? */ if( thread->threadState == WAIT_FOR_SEND ) { TCB *waitingThread; while( (waitingThread=popQueue( &thread->threadQueue )) != NULL ) { waitingThread->threadState = READY; attachRunQueue(waitingThread); } } else if( thread->threadState == WAIT_FOR_RECV ) { assert( thread->waitThread != NULL ); // XXX: Why? detachQueue( &thread->waitThread->threadQueue, thread ); } memset(thread, 0, sizeof *thread); thread->threadState = DEAD; enqueue(&freeThreadQueue, thread); return 0; }