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; }
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; } } } } }
/** * Fonction de sauvegarde et d'envoi des données au serveur */ void save_network(Project *project, Device *device) { gushort i; char *packet; char *commands[4] = { "dhcpConfig", "deviceIPAddress", "subnetMask", "gateway"/*, "deviceMACAddress"*/ }; for(i=0; i<4; i++) { packet = formatPackets(3, device->name, commands[i], (i == 0) ? ((gtk_combo_box_get_active(GTK_COMBO_BOX(project->networksetup.entry[i])) == 0) ? "off" : "on") : gtk_entry_get_text(GTK_ENTRY(project->networksetup.entry[i]))); pushQueue(&project->server.sender_queue, packet, project->server.sender_lock); free(packet); } g_cond_broadcast(project->server.notifier); }
static void copyQueueItems(const struct Tamarama *t, const struct NFA *sub, struct mq *q1, struct mq *q2, const u32 activeIdx) { const u32 *baseTop = (const u32 *)((const char *)t + sizeof(struct Tamarama)); u32 lower = baseTop[activeIdx]; u32 upper = activeIdx == t->numSubEngines - 1 ? ~0U : baseTop[activeIdx + 1]; u32 event_base = isMultiTopType(sub->type) ? MQE_TOP_FIRST : MQE_TOP; while (q1->cur < q1->end) { u32 type = q1->items[q1->cur].type; s64a loc = q1->items[q1->cur].location; DEBUG_PRINTF("type:%u lower:%u upper:%u\n", type, lower, upper); if (type >= lower && type < upper) { u32 event = event_base; if (event == MQE_TOP_FIRST) { event += type - lower; } pushQueue(q2, event, loc); } else { pushQueueNoMerge(q2, MQE_END, loc); break; } q1->cur++; } }
void AsyncCraqGet::get(const CraqDataSetGet& dataToGet, OSegLookupTraceToken* traceToken) { // Duration beginGetEnqueueManager = Time::local() - Time::epoch(); // traceToken->getManagerEnqueueBegin = // beginGetEnqueueManager.toMicroseconds(); traceToken->stamp(OSegLookupTraceToken::OSEG_TRACE_GET_MANAGER_ENQUEUE_BEGIN); CraqDataSetGet* cdQuery = new CraqDataSetGet(dataToGet.dataKey,dataToGet.dataKeyValue,dataToGet.trackMessage,CraqDataSetGet::GET); QueueValue* qValue = new QueueValue; qValue->cdQuery = cdQuery; qValue->traceToken = traceToken; pushQueue(qValue); // Duration endGetEnqueueManager = Time::local() - Time::epoch(); // traceToken->getManagerEnqueueEnd = endGetEnqueueManager.toMicroseconds(); traceToken->stamp(OSegLookupTraceToken::OSEG_TRACE_GET_MANAGER_ENQUEUE_END); int numTries = 0; while((mQueue.size()!= 0) && (numTries < CRAQ_MAX_PUSH_GET)) { ++numTries; int rand_connection = rand() % STREAM_CRAQ_NUM_CONNECTIONS_GET; checkConnections(rand_connection); } }
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; }
//-------------------------------------------------------------- bool goThreadedVideo::loadMovie(string _name) { if (!isSetup) setup(); // make sure that... if(!isThreadRunning() // ...the thread is not already running... && loaded[cueVideo] // ...that the cueVideo is loaded... && loaded[currentVideo] // ...that the currentVideo is loaded... && textured[cueVideo] // ...and that both && textured[currentVideo] // are textured... && !loading // ...and that no other instance is also loading (this is optional, but recommended ;-) ) { loading = true; // flag all instances that we are loading (see above) videoRequests++; // use a counter to switch between cue and current video[] player indexs if(videoRequests % MAX_VIDEOS != currentVideo || firstLoad) { // ie., this toggles which of the video[] players is // the cue or current index (also handles a "firstload") cueVideo = videoRequests % MAX_VIDEOS; // set the cueVideo index name[cueVideo] = _name; // set the video to load name ofLog(OF_LOG_VERBOSE, "Loading: " + _name); video[cueVideo]->setUseTexture(false); // make sure the texture is turned off or else the thread crashes: openGL is thread safe! loaded[cueVideo] = false; // set flags for loaded (ie., quicktime loaded) textured[cueVideo] = false; // and textured (ie., "forced texture" once the thread is stop) startThread(false, false); // start the thread return true; // NB: this does not let us know that the video is loaded; just that it has STARTED loading... } else { // ELSE: the video has not been textured and/or updated yet (ie., we // have to wait one cycle between the thread terminating and the texture // being "forced" back on - otherwise openGL + thread = crash... ofLog(OF_LOG_VERBOSE, "Load BLOCKED by reload before draw/update"); goVideoError err = GO_TV_UPDATE_BLOCKED; ofNotifyEvent(error, err); return false; } } else { // ELSE: either we're already loading in this instance OR another instance ofLog(OF_LOG_VERBOSE, "Load BLOCKED by already thread loading...attempting to enqueue"); #ifdef USE_QUEUE pushQueue(_name); return true; #else goVideoError err = GO_TV_LOAD_BLOCKED; ofNotifyEvent(error, err); return false; #endif } }
/*! * @brief Motager "Exit Callback" fra I2C * @details En "Interrupt Service Routine(ISR)" der aktiveres ved færdig modtagelse af kald via I2C-busset, det modtaget data behandles og håndteres. * @public * @memberof I2C * @author Jeppe Stærk ([email protected]) */ void I2CS_I2C_ISR_ExitCallback() { if(I2CS_I2CSlaveGetWriteBufSize() == I2C_BUFFER_SIZE) { DEBUG_PutCRLF(); DEBUG_PutString("** isr exit callback **"); DEBUG_PutCRLF(); DEBUG_PutString("I> i2cRxBuffer[0]: "); DEBUG_PutHexByte(i2cRxBuffer[0]); DEBUG_PutString(" [1]: "); DEBUG_PutHexByte(i2cRxBuffer[1]); DEBUG_PutString(" [2]: "); DEBUG_PutHexByte(i2cRxBuffer[2]); DEBUG_PutString(" [3]: "); DEBUG_PutHexByte(i2cRxBuffer[3]); DEBUG_PutString(" buffer size: "); DEBUG_PutHexByte(I2CS_I2CSlaveGetWriteBufSize()); DEBUG_PutCRLF(); struct Action action; action.cmd = i2cRxBuffer[I2C_PACKET_CMD_POS]; action.val = i2cRxBuffer[I2C_PACKET_VAL_POS]; switch(i2cRxBuffer[I2C_PACKET_CMD_POS]) { case CMD_SET_Z_POS : dataZ.isrStopZ = 1; DEBUG_PutString(") isrStopZ = 1"); DEBUG_PutCRLF(); pushQueue(action); break; default : pushQueue(action); break; } I2CS_I2CSlaveClearWriteBuf(); (void) I2CS_I2CSlaveClearWriteStatus(); } }
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_Read(int fd, void *buf, size_t count) { struct QPacket pkt; size_t rdBytes = 0; pkt.data.buf = buf; pkt.sz = count; while ((readQueue.numElem < readQueue.elemArrSz) && (rdBytes < count)) { pushQueue(&readQueue, pkt); pkt.data.buf = (char*)pkt.data.buf + 1; rdBytes++; } return rdBytes; }
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; }
//will be posted to from different connections. am responsible for deleting. void AsyncCraqGet::erroredGetValue(CraqOperationResult* errorRes) { if (errorRes->whichOperation == CraqOperationResult::GET) { QueueValue * qVal = new QueueValue; CraqDataSetGet* cdSG = new CraqDataSetGet (errorRes->objID,errorRes->servID,errorRes->tracking, CraqDataSetGet::GET); qVal->cdQuery = cdSG; qVal->traceToken = errorRes->traceToken; pushQueue(qVal); } else { #ifdef ASYNC_CRAQ_GET_DEBUG std::cout<<"\n\nShould never be receiving an error result for a set in asyncCraqGet.cpp\n\n"; #endif assert(false); } delete errorRes; }
/** * Fonction de redémarrage d'un device */ void restart_device_cb(GtkButton *button, Project *project) { GtkWidget *dialog; Device *device; char *packet; guint result; device = (Device *)g_object_get_data(G_OBJECT(button), "device"); dialog = gtk_message_dialog_new(GTK_WINDOW(project->networksetup.dialog), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, "\nAre you sure to restart the device ?"); gtk_window_set_title(GTK_WINDOW(dialog), "Restart the device"); result = gtk_dialog_run(GTK_DIALOG(dialog)); switch(result) { case GTK_RESPONSE_YES : { packet = formatPackets(3, device->name, "restartDevice", "on"); pushQueue(&project->server.sender_queue, packet, project->server.sender_lock); g_cond_broadcast(project->server.notifier); free(packet); gtk_widget_destroy(dialog); gtk_widget_destroy(project->networksetup.dialog); break; } case GTK_RESPONSE_NO : gtk_widget_destroy(dialog); break; } }
//All threads require void functions void fillQThread(struct queue* localQ) { fillThreadRunning = true; FILE* codeFile = fopen(__FILE__, "r"); int c = 0, b; //c is count, b is byte (once we fill the file, or we reach the end of the queue) b = getc(codeFile); while(c < localQ->max || b != EOF) //While count is less than max or we have not reached EOF { sleep(rand() % 50); //Sleep randomly between 0 and 49 milliseconds while(queueIsProcessing) {} //While other routine is processing, just chill, as soon as it's done, jump in queueIsProcessing = true; //Lock for my local push pushQueue(localQ, b); //Passed in as a pointer, with the input value as the current byte in the file c++; b = getc(codeFile); queueIsProcessing = false; //Release } fclose(codeFile); fillThreadRunning = false; pthread_exit(NULL); }
/////////////////////////////////////////////////////////////////////////////// // // MAIN // /////////////////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { // Обработка сигнала struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = handleSigInt; sigaction(SIGINT, &act, 0); // Проверка количества аргументов if (argc < 4) { fprintf(stderr, "Too few arguments\n"); exit(EXIT_FAILURE); } // Количество потоков - 1й параметр запуска int numberOfWorkers = atoi(argv[1]); // Порт - 2й параметр запуска char port[4]; strcpy(port, argv[2]); // Путь к файлу с паролями - 3й параметр запуска readPasswordsFromFile(argv[3]); // Инициализация connections memset(connections, 0, sizeof(connections)); struct addrinfo* addresses = getAvailableAddresses(port); if (!addresses) exit(EXIT_FAILURE); // Получаем дескриптор сокета int _socketfd = getSocket(addresses); if (_socketfd == -1) { exit(EXIT_FAILURE); } setSocketFd(_socketfd); // Начинаем слушать сокет if (listen(socketfd, SOMAXCONN) == -1) { perror("listen\n"); exit(EXIT_FAILURE); } // Создаём потоки pthread_t workers[numberOfWorkers]; pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mutex, &mutexattr); pthread_mutex_init(&connectionsMutex, &mutexattr); pthread_cond_t condition; pthread_cond_init(&condition, NULL); // Создаём отдельный поток для отслеживания таймаута соединений pthread_t timeoutWatcher; pthread_create(&timeoutWatcher, NULL, watchTimeout, NULL); // Создаём очередь struct Queue queue; initQueue(&queue, sizeof(struct epoll_event)); struct WorkerArgs workerArgs; initWorkerArgs(&workerArgs, &queue, &mutex, &condition); for (int i = 0; i < sizeof(workers) / sizeof(pthread_t); i++) { pthread_create(&workers[i], NULL, worker, (void *) &workerArgs); } // Создаём epoll int _epollfd = epoll_create1(0); if (_epollfd == -1) { perror("epoll_create error\n"); exit(EXIT_FAILURE); } setEpollFd(_epollfd); // Добавляем сокет в epoll if (addToEpoll(epollfd, socketfd, EPOLLET | EPOLLIN) == -1) exit(EXIT_FAILURE); int maxEventNum = numberOfWorkers; struct epoll_event events[maxEventNum]; int timeout = -1; printf("Main thread: %d\n", (int)pthread_self()); while(!done) { int eventsNumber = epoll_wait(epollfd, events, maxEventNum, timeout); if (!eventsNumber) printf("No events\n"); for (int i = 0; i < eventsNumber; i++) { pthread_mutex_lock(&mutex); pushQueue(&queue, &events[i]); pthread_cond_signal(&condition); pthread_mutex_unlock(&mutex); } } // Освобождение ресурсов pthread_mutex_destroy(&connectionsMutex); pthread_mutex_destroy(&mutex); pthread_mutexattr_destroy(&mutexattr); free(passPairs); destroyQueue(&queue); close(socketfd); close(epollfd); printf("DONE!!!"); return 0; }
hwlmcb_rv_t roseHandleChainMatch(const struct RoseEngine *t, struct hs_scratch *scratch, u32 event, u64a top_squash_distance, u64a end, char in_catchup) { assert(event == MQE_TOP || event >= MQE_TOP_FIRST); struct core_info *ci = &scratch->core_info; u8 *aa = getActiveLeafArray(t, scratch->core_info.state); u32 aaCount = t->activeArrayCount; struct fatbit *activeQueues = scratch->aqa; u32 qCount = t->queueCount; const u32 qi = 0; /* MPV is always queue 0 if it exists */ struct mq *q = &scratch->queues[qi]; const struct NfaInfo *info = getNfaInfoByQueue(t, qi); s64a loc = (s64a)end - ci->buf_offset; assert(loc <= (s64a)ci->len && loc >= -(s64a)ci->hlen); if (!mmbit_set(aa, aaCount, qi)) { initQueue(q, qi, t, scratch); nfaQueueInitState(q->nfa, q); pushQueueAt(q, 0, MQE_START, loc); fatbit_set(activeQueues, qCount, qi); } else if (info->no_retrigger) { DEBUG_PRINTF("yawn\n"); /* nfa only needs one top; we can go home now */ return HWLM_CONTINUE_MATCHING; } else if (!fatbit_set(activeQueues, qCount, qi)) { initQueue(q, qi, t, scratch); loadStreamState(q->nfa, q, 0); pushQueueAt(q, 0, MQE_START, 0); } else if (isQueueFull(q)) { DEBUG_PRINTF("queue %u full -> catching up nfas\n", qi); /* we know it is a chained nfa and the suffixes/outfixes must already * be known to be consistent */ if (ensureMpvQueueFlushed(t, scratch, qi, loc, in_catchup) == HWLM_TERMINATE_MATCHING) { DEBUG_PRINTF("terminating...\n"); return HWLM_TERMINATE_MATCHING; } } if (top_squash_distance) { assert(q->cur != q->end); struct mq_item *last = &q->items[q->end - 1]; if (last->type == event && last->location >= loc - (s64a)top_squash_distance) { last->location = loc; goto event_enqueued; } } pushQueue(q, event, loc); event_enqueued: if (q_cur_loc(q) == (s64a)ci->len) { /* we may not run the nfa; need to ensure state is fine */ DEBUG_PRINTF("empty run\n"); pushQueueNoMerge(q, MQE_END, loc); char alive = nfaQueueExec(q->nfa, q, loc); if (alive) { scratch->tctxt.mpv_inactive = 0; q->cur = q->end = 0; pushQueueAt(q, 0, MQE_START, loc); } else { mmbit_unset(aa, aaCount, qi); fatbit_unset(scratch->aqa, qCount, qi); } } DEBUG_PRINTF("added mpv event at %lld\n", loc); scratch->tctxt.next_mpv_offset = 0; /* the top event may result in matches * earlier than expected */ return HWLM_CONTINUE_MATCHING; }
int main(int argc,char* argv[]){ printf("\nPROGRAM BEGUN\n"); //generating a readable .txt file srand(time(NULL)); FILE* out = fopen(argv[2],"w"); int i; int v1; int v2; float v3; for(i = 0;i < atoi(argv[1]);i++){ v1 = rand() % 100; v2 = rand() % 200; v3 = (rand() % 10000)/100.00; fprintf(out,"%d %d %f\n",v1,v2,v3); } fclose(out); //opening the generated .txt file w/ read privileges //then reading the data structures into a stack FILE* read = fopen(argv[2],"r"); stack* s = createStack(); data* d = malloc(sizeof(data)); while(1){ d = readData(read); if(d == NULL){ break; } pushStack(s,d); } //printing the stack printf("\nPRINTING STACK\n\n"); printStack(s); //creating a queue and pushing the data from the stack to it dnode* tempN = frontStack(s); queue* q = createQueue(); //remember that to do this we must: //1. begin a while loop that runs while [emptyStack(s) != 0] //2. set a temp dnode equal to the head of the stack //3. create a NEW data structure from the data within this temp dnode //4. use the pushQueue function with this newly created data struct //5. pop the front element off of the stack, effectively deleting it while(emptyStack(s) != 1){ tempN = frontStack(s); d = createData(tempN->d->i1,tempN->d->i2,tempN->d->f1); pushQueue(q,d); popStack(s); } //printing the queue printf("\nPRINTING QUEUE\n\n"); printQueue(q); if(emptyStack(s) == 1){ printf("\nSTACK EMPTY\n\n"); } return 0; }
bool kThreadClipView::addClips(vector< shared_ptr<Clip> > _clips){ if(!isThreadRunning() // ...the thread is not already running... // && loaded[cueVideo] // ...that the cueVideo is loaded... // && loaded[currentVideo] // ...that the currentVideo is loaded... // && textured[cueVideo] // ...and that both // && textured[currentVideo] // are textured... // && !loading // ...and that no other instance is also loading (this is optional, but recommended ;-) ) { clearClips(); loadClips.clear(); for (int i=0; i<_clips.size(); i++) { loadClips.push_back( _clips[i] ); } cout << "LOADES: : " << loadClips.size() << endl; startThread(false, false); // start the thread return true; // NB: this does not let us know that the video is loaded; just that it has STARTED loading... // // } else { // ELSE: the video has not been textured and/or updated yet (ie., we // // have to wait one cycle between the thread terminating and the texture // // being "forced" back on - otherwise openGL + thread = crash... // ofLog(OF_LOG_VERBOSE, "Load BLOCKED by reload before draw/update"); // goVideoError err = GO_TV_UPDATE_BLOCKED; // ofNotifyEvent(error, err); // return false; // } } else { // ELSE: either we're already loading in this instance OR another instance ofLog(OF_LOG_VERBOSE, "Load BLOCKED by already thread loading...attempting to enqueue"); #ifdef USE_QUEUE pushQueue(_name); return true; #else // goVideoError err = GO_TV_LOAD_BLOCKED; // ofNotifyEvent(error, err); return false; #endif } /*shared_ptr<kClipShow> clip; for (int i=0; i<_clips.size(); i++) { clip = make_shared<kClipShow>(); clip -> setClip( _clips[i] ); clip->set( 0, 0, CLIPVIEW_SIZE, CLIPVIEW_SIZE ); kScrollView::addWidget( clip ); } kScrollView::arrangeWidgets();*/ }