int bfs(int s,int a, struct vertex *adj) { int i, u, j, l, v, w, k; struct queue *queue = malloc(sizeof(struct queue)); struct queue *queueHyphen = malloc(sizeof(struct queue)); queueInit(queue); queueInit(queueHyphen); #pragma omp parallel for shared(adj) for (i = 0; i < adj[s].indeg; i++) { //par begin //compare ok u = adj[s].ins[i].u; j = adj[s].ins[i].iuout; eliminate(adj, u, j); //compare ok } //par end //compare ok l = 0; //compare ok adj[s].traversal = a; //compare ok adj[s].distance = l; //compare ok //before was adj[s].distance = l //compare with php struct queueNode *queueNode1 = malloc(sizeof(struct queueNode)); enque(s, queue, queueNode1); //todo // printf("l74:queue -- should've queued %i\n", s); queueReset(queueHyphen); //todo // printf("l76:queueHypen -- should've reset"); while (true) { //repeat 1 begin l = l + 1; //compare ok while (true) { //repeat 2 begin u = deque(queue); //todo // printf("l81:queue -- should've dequeued %i\n", u); while (adj[u].first < adj[u].outdeg) { //compare ok i = adj[u].first; //compare ok v = adj[u].out[i]; //compare ok #pragma omp parallel for shared(adj) for (j = 0; j < adj[v].indeg; j++) { //par begin //compare ok w = adj[v].ins[j].u; k = adj[v].ins[j].iuout; eliminate(adj, w, k); //compare ok } //par end //compare ok a = a + 1; //compare ok adj[v].traversal = a; //compare ok adj[v].distance = l; //compare ok adj[v].parent = u; //compare ok // printf(":%i parent of %i\n", u, v); //comment me struct queueNode *queueNode2 = malloc(sizeof(struct queueNode)); enque(v, queueHyphen, queueNode2); //todo // printf("l103:queueHyphen -- should've queued %i\n", v); } //end while //compare ok if (isQueueEmpty(queue)) { //until break; } } //repeat 2 end //compare ok *queue = *queueHyphen; queueInit(queueHyphen); // printf("l121:queue = queueHyphen\n"); if (isQueueEmpty(queue)) { break; } } //end repeat 1 //compare ok return EXIT_SUCCESS; }
void BFS(int v) { for (int m = 0; m < n; m++) { visited[m] = 0; } int counter = 0; visited[v] = 1; queueInit(); Queuepush(v);//큐에 v를 넣어준다 fprintf(fout,"%d -> ", v); counter++; while (!QisEmpty()) { v = getFront();//front를 v에 넣는다 Queuepop(); for (int w = 0; w < n; w++) { if ((visited[w]==0) && adj_mat[v][w])//너비 탐색을 위해서 w가 다음 값을 계속 탐색해서 edge가 있으면 탐색시작한다 { Queuepush(w);//w를 push한다. visited[w] = 1;//방문한것으로 표시 fprintf(fout,"%d ", w );//출력 counter++; if (counter<n) fprintf(fout," -> "); } } } }
QueueClass *queueNew(int elementSize, int elementMaxCount) { QueueClass *queue = malloc(sizeof(QueueClass)); if (queue) { return queueInit(queue, elementSize, elementMaxCount); } return NULL; }
int main(int argc, char **argv) { int listenfd, *connfd, port, clientlen, i; struct sockaddr_in clientaddr; pthread_t tid; port_queue prod_var; /* Check command line args */ if (argc != 2) { fprintf(stderr, "usage: %s <port>\n", argv[0]); exit(1); } port = atoi(argv[1]); connfdqp = queueInit (); prod_var.port = port; prod_var.q = connfdqp; Pthread_create(&tid, NULL, producer, &prod_var); printf("Producer thread created %u\n", (unsigned int) tid); Pthread_detach(tid); printf ("Producer thread detached\n"); for (i = 0; i < MAXTHREAD; i++) { Pthread_create(&tid, NULL, consumer, connfdqp); printf("Consumer thread created %u\n", (unsigned int) tid); Pthread_detach(tid); printf("Consumer thread detached\n"); } printf("Main thread exited\n"); Pthread_exit(NULL); }
int main() { queueInit(); queueTest(); return 0; }
/** * \brief Setup resources for SPI transactions * * Called Once to setup buffers, locks, and GPIO * \returns * If Setup has been called recently, 1 is returned as a warning. \n * If GPIO can't be loaded, the entire system is stopped with EXIT_FAILURE. \n * Otherwise, 0 is returned. */ int spiSetup(void) { // Setup resources for SPI transactions FILE *FPTR; FPTR = popen("gpio load spi", "r"); fclose(FPTR); // FIXME: use SLAVE_INT_PIN here FPTR = popen("gpio export 2 in", "r"); fclose(FPTR); //syslog(LOG_DEBUG, "Using pin %i", SLAVE_INT_PIN); if (wiringPiSetupSys() == -1) { syslog(LOG_ERR, "Couldn't setup wiringPi system!"); exit(EXIT_FAILURE); } if (wiringPiISR(SLAVE_INT_PIN, INT_EDGE_FALLING, &sgSerialSlaveSending) < 0) { syslog(LOG_ERR, "Couldn't setup interrupt on pin!"); exit(EXIT_FAILURE); } pthread_mutex_init(&transfer_lock, NULL); if (tx_buffer == NULL) { tx_buffer = queueInit(100); } else { syslog(LOG_WARNING, "spiSetup has already been called!"); return 1; } return 0; }
/* * This is Resource file for all test parameters * Initialize start port to 10,000 * Set SERVER to point to server that we want to connect to * Set INTERFACE to point to our Network Interface * Set up a socket and connect to SERVER */ initCfg() { #define INTERFACE "eth0" #define SERVER "127.0.0.1" #define SSL_PORT 4433 cfg.startPort = 10000; // client src port start strcpy(cfg.utIP, SERVER); strcpy(cfg.interface, INTERFACE); cfg.sslPort = SSL_PORT; getSelfIP(); queueInit(); }
void initialize_threads() { pthread_t con; LOG_ERROR_ON_NULL(fifo = queueInit(), "main: Clean queue Init failed.\n"); LOG_ERROR_ON_NULL(cleaner_fifo = queueInit(), "main: Clean queue Init failed.\n"); dbgprintf("Creating threads\n"); int i; fd_mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(fd_mutex, NULL); for (i = 0; i < NOPE_THREADS; i++) { pthread_create(&con, NULL, &worker_thread, fifo); //con+=sizeof(pthread_t); } socketpair(AF_UNIX, SOCK_STREAM, 0, socketpair_fd); if (FCNTL_NONBLOCK(socketpair_fd[0]) < 0) perror("fcntl"); if (FCNTL_NONBLOCK(socketpair_fd[1]) < 0) perror("fcntl"); dbgprintf("Socketpair 1 %d and 2 %d \n", socketpair_fd[0], socketpair_fd[1]); }
int main ( void ) { fun_queue = queueInit(FUN_Q_LEN); rx_pay_queue = pqInit(12); //replace 12 with a #define const later test_function tf; /* Initialization */ SetupClock(); SwitchClocks(); SetupPorts(); SetupInterrupts(); SetupI2C(); SetupADC(); SetupTimer1(); SetupPWM(); SetupTimer2(); gyroSetup(); xlSetup(); dfmemSetup(); WordVal pan_id = {RADIO_PAN_ID}; WordVal src_addr = {RADIO_SRC_ADDR}; WordVal dest_addr = {RADIO_DEST_ADDR}; radioInit(src_addr, pan_id, RADIO_RXPQ_MAX_SIZE, RADIO_TXPQ_MAX_SIZE); radioSetDestAddr(dest_addr); radioSetChannel(RADIO_MY_CHAN); char j; for(j=0; j<3; j++){ LED_2 = ON; delay_ms(500); LED_2 = OFF; delay_ms(500); } LED_2 = ON; EnableIntT2; while(1){ while(!queueIsEmpty(fun_queue)) { rx_payload = pqPop(rx_pay_queue); tf = (test_function)queuePop(fun_queue); (*tf)(payGetType(rx_payload), payGetStatus(rx_payload), payGetDataLength(rx_payload), payGetData(rx_payload)); payDelete(rx_payload); } } return 0; }
USBCDCClass *usbCdcClassInit(USBCDCClass *usbCdc, USBDriverClass *usb, int txBufferSize, int rxBufferSize, uint8_t bulkOutEp, uint16_t bulkOutChunkSize, uint8_t bulkInEp, uint16_t bulkInChunkSize, uint8_t intrInEp, uint16_t intrInChunkSize) { IO_STREAM_CLASS(usbCdc)->writeTimeout = USBCDCClass_writeTimeout; IO_STREAM_CLASS(usbCdc)->readTimeout = USBCDCClass_readTimeout; IO_STREAM_CLASS(usbCdc)->flush = USBCDCClass_flush; IO_STREAM_CLASS(usbCdc)->close = USBCDCClass_close; queueInit(&usbCdc->txQueue, 1, txBufferSize); queueInit(&usbCdc->rxQueue, 1, rxBufferSize); usbCdc->usb = usb; usbCdc->bulkOutChunkSize = bulkOutChunkSize; usbCdc->bulkInChunkSize = bulkInChunkSize; usbCdc->intrInChunkSize = intrInChunkSize; usbCdc->bulkOutEp = bulkOutEp; usbCdc->bulkInEp = bulkInEp; usbCdc->intrInEp = intrInEp; usbCdc->lastChunkSize = 0; USBDriverHooks *hooks = calloc(1, sizeof(USBDriverHooks)); hooks->arg = usbCdc; hooks->resetHook = USBCDCClass_resetHook; hooks->setConfigHook = USBCDCClass_setConfigHook; hooks->setupRequestHook = USBCDCClass_setupRequestHook; usbDriverRegisterHooks(usb, hooks); return usbCdc; }
int main () { queue *fifo; pthread_t pro, con; fifo = queueInit (); if (fifo == NULL) { fprintf (stderr, "main: Queue Init failed.\n"); exit (1); } pthread_create (&pro, NULL, producer, fifo); pthread_create (&con, NULL, consumer, fifo); pthread_join (pro, NULL); pthread_join (con, NULL); queueDelete (fifo); return 0; }
/*Main function */ int main () { queue *fifo; pthread_t pro, con; /*QUEUE initialization */ fifo = queueInit (); if (fifo == NULL) { fprintf (stderr, "main: Queue Init failed.\n"); exit (1); } /*producer thread creation */ ret_count=pthread_create (&pro, NULL, producer, fifo); if(ret_count) { printf("\n ERROR : Return code from pthread_create() is %d ",ret_count); exit(-1); } /*consumer thread creation */ ret_count=pthread_create (&con, NULL, consumer, fifo); if(ret_count) { printf("\n ERROR : Return code from pthread_create() is %d ",ret_count); exit(-1); } /*joining producer thread to main thread */ ret_count=pthread_join (pro, NULL); if(ret_count) { printf("\n ERROR : Return code from pthread_join() is %d ",ret_count); exit(-1); } /*joining consumer thread to main thread */ ret_count=pthread_join (con, NULL); if(ret_count) { printf("\n ERROR : Return code from pthread_join() is %d ",ret_count); exit(-1); } queueDelete (fifo); return 0; }
int main(int argc, char *argv[]) { int port = 0; if (argc !=2) { printf("Usage: ./rs <port number>\n"); return 1; } port = atoi(argv[1]); if (port<2000 || port>65535) { printf("port must be an integer between 2000 and 65535\n"); printf("invalid value %i", port); return 1; } queue *fifo; pthread_t srv, app; fifo = queueInit(); if (fifo==NULL) { printf("queueInit failed\n"); exit (1); } queueAdd(fifo, port); pthread_create(&srv, NULL, TCPServer, fifo); pthread_create(&app, NULL, ThreeDeeApp, fifo); pthread_join(srv, NULL); pthread_join(app, NULL); queueDelete(fifo); return 0; }
int main() { int i = 0; //int *queuedata; void * dataout; //void * dummyqueuezero = &dataqueue[1]; //void * dummyqueueone = &dataqueue[1]; queueInit(&queueTest, QUEUESIZE-1); while( queueEnqueue(&queueTest, &dataqueue[i]) == noError) { i++; } while( queueDequeue(&queueTest, &dataout) == noError) { //queuedata = dataout; //blaat = *(int *) dataout; printf("dequeued element %d\n", *((int *) dataout)); } return 0; }
afLib::afLib(const int mcuInterrupt, isr isrWrapper, onAttributeSet attrSet, onAttributeSetComplete attrSetComplete, Stream *theLog, afSPI *theSPI) { queueInit(); _theLog= theLog; _theSPI= theSPI; _request.p_value = NULL; //_spiSettings = SPISettings(1000000, LSBFIRST, SPI_MODE0); _interrupts_pending = 0; _state = STATE_IDLE; _writeCmd = NULL; _writeCmdOffset = 0; _outstandingSetGetAttrId = 0; _readCmd = NULL; _readCmdOffset = 0; _readBufferLen = 0; _txStatus = new StatusCommand(_theLog); _rxStatus = new StatusCommand(_theLog); _onAttrSet = attrSet; _onAttrSetComplete = attrSetComplete; _theSPI->begin(); // AJS where does this get moved to?? #ifdef ARDUINO pinMode(mcuInterrupt, INPUT); attachInterrupt(mcuInterrupt, isrWrapper, FALLING); #endif }
void queueReset(struct queue *pQueue) { queueInit(pQueue); }
PASTIX_INT simuInit(SimuCtrl *simuctrl, SymbolMatrix *symbptr, PASTIX_INT clustnbr, PASTIX_INT procnbr, PASTIX_INT cblknbr, PASTIX_INT bloknbr, Cand *candtab) { PASTIX_INT i, j; PASTIX_INT p; PASTIX_INT ftgtcur; PASTIX_INT candnbr; PASTIX_INT step; simuctrl->cblknbr = cblknbr; simuctrl->ftgtprio = 0; simuctrl->tasktab = NULL; simuctrl->ftgtcnt = 0; /** Processor initialisation **/ MALLOC_INTERN(simuctrl->proctab, procnbr, SimuProc); for(i=0;i<procnbr;i++) { timerSet(TIMER(i), 0.0); /** for paragraph numeric tolerance **/ simuctrl->proctab[i].prionum = 0; MALLOC_INTERN(simuctrl->proctab[i].taskheap, 1, Queue); MALLOC_INTERN(simuctrl->proctab[i].taskheap2, 1, Queue); queueInit(simuctrl->proctab[i].taskheap, 100); queueInit(simuctrl->proctab[i].taskheap2, 100); MALLOC_INTERN(simuctrl->proctab[i].tasktab, 1, ExtendVectorINT); extendint_Init(simuctrl->proctab[i].tasktab, bloknbr/procnbr + 1); } /** Cluster initialization **/ MALLOC_INTERN(simuctrl->clustab, clustnbr, SimuCluster); step = procnbr / clustnbr; for(i=0;i<clustnbr;i++) { simuctrl->clustab[i].fprocnum = i*step; simuctrl->clustab[i].lprocnum = simuctrl->clustab[i].fprocnum + step - 1; MALLOC_INTERN(simuctrl->clustab[i].ftgtsend, clustnbr, ExtendVectorINT); simuctrl->clustab[i].prionum = 0; for(p=0;p<clustnbr;p++) extendint_Init(&(simuctrl->clustab[i].ftgtsend[p]), cblknbr/(2*clustnbr)+1); } simuctrl->clustab[clustnbr-1].lprocnum = procnbr-1; MALLOC_INTERN(simuctrl->ownetab, cblknbr, PASTIX_INT); MALLOC_INTERN(simuctrl->blprtab, bloknbr, PASTIX_INT); /* affect a negative value to cblk not mapped */ for(i=0;i<cblknbr;i++) simuctrl->ownetab[i] = -1; for(i=0;i<bloknbr;i++) simuctrl->blprtab[i] = -1; MALLOC_INTERN(simuctrl->cblktab, cblknbr+1, SimuCblk); MALLOC_INTERN(simuctrl->bloktab, bloknbr+1, SimuBlok); ftgtcur = 0; for(i=0;i<cblknbr;i++) { candnbr = candtab[i].lccandnum - candtab[i].fccandnum + 1; simuctrl->cblktab[i].ctrbcnt = 0; for(j=symbptr->cblktab[i].bloknum;j<symbptr->cblktab[i+1].bloknum;j++) { simuctrl->bloktab[j].ftgtnum = ftgtcur; simuctrl->bloktab[j].tasknum = -1; simuctrl->bloktab[j].ctrbcnt = 0; /*if(candnbr > 1)*/ ftgtcur += candnbr; } } /* one extracblk for avoiding side effect */ simuctrl->bloktab[bloknbr].ftgtnum = ftgtcur; simuctrl->ftgtnbr = ftgtcur; if(simuctrl->ftgtnbr > 0) { /** Allocate and Initialize the timer for the reception of each ftgt on a candidate cluster **/ MALLOC_INTERN(simuctrl->ftgttimetab, simuctrl->ftgtnbr, SimuTimer); for(i=0;i<simuctrl->ftgtnbr;i++) timerSet(&(simuctrl->ftgttimetab[i]), 0.0); MALLOC_INTERN(simuctrl->ftgttab, ftgtcur, SimuFtgt); for(i=0;i<simuctrl->ftgtnbr;i++) { simuctrl->ftgttab[i].clustnum = -1; timerSet(&(simuctrl->ftgttab[i].timerecv), 0.0); simuctrl->ftgttab[i].costsend = 0.0; simuctrl->ftgttab[i].costadd = 0.0; bzero(simuctrl->ftgttab[i].ftgt.infotab,MAXINFO*sizeof(PASTIX_INT)); simuctrl->ftgttab[i].ftgt.infotab[FTGT_FCOLNUM] = INTVALMAX; simuctrl->ftgttab[i].ftgt.infotab[FTGT_FROWNUM] = INTVALMAX; simuctrl->ftgttab[i].ftgt.infotab[FTGT_CTRBNBR] = 0; simuctrl->ftgttab[i].ftgt.infotab[FTGT_CTRBCNT] = 0; } } else { simuctrl->ftgttab = NULL; simuctrl->tasktimetab = NULL; simuctrl->ftgttimetab = NULL; } return 1; }
// to_goalがtrueのとき、ゴールまでの経路を探索する // to_goalがfalseのとき、未探索の地点までの経路を探索する enum action_t agent_explore(void) { queueInit(); for(int y = 0; y < size; ++y) { for(int x = 0; x < size; ++x) { if(check_goal(y, x)) { d[y][x] = 0; inQueue[y][x] = true; queueEnqueue(y, x); } else { d[y][x] = UCHAR_MAX - 1; inQueue[y][x] = false; } } } while(queueEmpty() == false) { int vy, vx; queueDequeue(&vy, &vx); inQueue[vy][vx] = false; for (int k = 0; k < 4; k++) { if (wall[vy][vx][k] == false) { int ny = vy + dy[k]; int nx = vx + dx[k]; if(d[ny][nx] > d[vy][vx] + 1) { d[ny][nx] = d[vy][vx] + 1; if(inQueue[ny][nx] == false) { inQueue[ny][nx] = true; queueEnqueue(ny, nx); } } } } } if(wall[curY][curX][(dir + 0)%4] == false && d[curY + dy[(dir + 0)%4]][curX + dx[(dir + 0)%4]] + 1 == d[curY][curX]) { // GoForward curY += dy[dir]; curX += dx[dir]; return GO_FORWARD; } if(wall[curY][curX][(dir + 1)%4] == false && d[curY + dy[(dir + 1)%4]][curX + dx[(dir + 1)%4]] + 1 == d[curY][curX]) { // TurnLeft dir = (dir + 1) % 4; return TURN_LEFT; } if(wall[curY][curX][(dir + 3)%4] == false && d[curY + dy[(dir + 3)%4]][curX + dx[(dir + 3)%4]] + 1 == d[curY][curX]) { // TurnRight dir = (dir + 3) % 4; return TURN_RIGHT; } if(wall[curY][curX][(dir + 2)%4] == false && d[curY + dy[(dir + 2)%4]][curX + dx[(dir + 2)%4]] + 1 == d[curY][curX]) { // TurnLeft dir = (dir + 1) % 4; return TURN_LEFT; } return NO_OPERATION; }
int *distancias(int n, int **A, int c) /* Recebe o número de cidades, uma matriz com os caminhos e a cidade a ser analisada (c). Devolve um vetor com as dis- tâncias até todas as cidades */ { int *d = mallocSafe(n*sizeof(int)); /* Matriz das distâncias */ int j; /* contador */ queueInit(n); /* Criamos a fila */ for(j = 0; j < n; j++) d[j] = n; /* Inicializa a matriz das distân- cias com 'n' - o número de ci- dades, que representa a dis- tância "infinita" */ d[c] = 0; /* A cidade a ser analisada tem distância dela a ela mesma com 0. */ queuePut(c); /* O primeiro elemento da fila, que será analisada, é a ci- dade passada como parâmetro. */ while(!queueEmpty()) /* Este laço é feito no MÁXIMO 'n' vezes, pois cada cidade é colocada na fila, para ter as distâncias analisadas, uma vez apenas */ { int i = queueGet(); /* Pegamos o primeiro elemento da fila */ for(j = 0; j < n; j++) /* Executamos este laço 'n' vezes no MÁXIMO, pois este é o número d checa- gens para os caminhos que faremos na matriz. */ if(s[i][j] == 1 && d[j] == n) { /* Se já tiver sido posto, no passado, é porque já houve um caminho mais curto até lá. Caso con- trário, se houver liga- ção (s[i][j] == 1) e não tiver sido posto ain- da (d[j] == n), fazemos as operações abaixo */ d[j] = d[i] + 1; /* A distância da cidade será a distância até a cidade atual (d[j]) somada de 1. */ queuePut(j); /* Se não tiver entrado ainda, ele é colocado na fila para ser ana- lisado posteriormen- te. */ } /* fim do if */ } /* fim do for */ } /* fim do while */
/*************************************************** * Main allocates structures, creates threads, * * waits to tear down. * ***************************************************/ int main (int argc, char *argv[]) { pthread_t *con; int cons; int *concount; queue *fifo; int i; pthread_t *pro; int *procount; int pros; pcdata *thread_args; /* * Check the number of arguments and determine the numebr of * producers and consumers */ if (argc != 3) { printf("Usage: producer_consumer number_of_producers number_of_consumers\n"); exit(0); } pros = atoi(argv[1]); cons = atoi(argv[2]); /* * Create the shared queue */ fifo = queueInit (); if (fifo == NULL) { fprintf (stderr, "main: Queue Init failed.\n"); exit (1); } /* * Create a counter tracking how many items were produced, shared * among all producers, and one to track how many items were * consumed, shared among all consumers. */ procount = (int *) malloc (sizeof (int)); if (procount == NULL) { fprintf(stderr, "procount allocation failed\n"); exit(1); } concount = (int *) malloc (sizeof (int)); if (concount == NULL) { fprintf(stderr, "concount allocation failed\n"); exit(1); } /* * Create arrays of thread structures, one for each producer and * consumer */ pro = (pthread_t *) malloc (sizeof (pthread_t) * pros); if (pro == NULL) { fprintf(stderr, "pros\n"); exit(1); } con = (pthread_t *) malloc (sizeof (pthread_t) * cons); if (con == NULL) { fprintf(stderr, "cons\n"); exit(1); } /* * Create the specified number of producers */ for (i=0; i<pros; i++){ /* * Allocate memory for each producer's arguments */ thread_args = (pcdata *)malloc (sizeof (pcdata)); if (thread_args == NULL) { fprintf (stderr, "main: Thread_Args Init failed.\n"); exit (1); } /* * Fill them in and then create the producer thread */ thread_args->q = fifo; thread_args->count = procount; thread_args->tid = i; pthread_create (&pro[i], NULL, producer, thread_args); } /* * Create the specified number of consumers */ for (i=0; i<cons; i++){ /* * Allocate space for next consumer's args */ thread_args = (pcdata *)malloc (sizeof (pcdata)); if (thread_args == NULL) { fprintf (stderr, "main: Thread_Args Init failed.\n"); exit (1); } /* * Fill them in and create the thread */ thread_args->q = fifo; thread_args->count = concount; thread_args->tid = i; pthread_create (&con[i], NULL, consumer, thread_args); } /* * Wait for the create producer and consumer threads to finish * before this original thread will exit. We wait for all the * producers before waiting for the consumers, but that is an * unimportant detail. */ for (i=0; i<pros; i++) pthread_join (pro[i], NULL); for (i=0; i<cons; i++) pthread_join (con[i], NULL); /* * Delete the shared fifo, now that we know there are no users of * it. Since we are about to exit we could skip this step, but we * put it here for neatness' sake. */ queueDelete (fifo); return 0; }
PayQueue pqInit(int max_size) { Queue pq = queueInit(max_size); return pq; }
void makeEmptyStack() { return queueInit(); }
int main() { int i, j, k, nNodes, nEdges, initialNode, finalNode, nCritAreas, nCritPoints, criticPoint, *results, trash = 0; trash = scanf(" %d %d", &nNodes, &nEdges); graph.nNodes = nNodes; graph.neighbors = (int **) malloc(sizeof(int *) * nNodes); graph.nNeighbors = (int *) malloc(sizeof(int) * nNodes); graph.nodesInSearch = (int **) malloc(sizeof(int *) * nNodes); queueInit(nNodes); parent = (int *) malloc(sizeof(int) * nNodes); visited = (int *) malloc(sizeof(int) * nNodes); for(i=0; i<nNodes; i++) { graph.nNeighbors[i] = 0; graph.neighbors[i] = NULL; graph.nodesInSearch[i] = NULL; parent[i] = -1; visited[i] = -1; } for (i=0; i<nEdges; i++) { trash = scanf(" %d %d", &initialNode, &finalNode); graph.neighbors[initialNode] = realloc(graph.neighbors[initialNode], sizeof(int) * (graph.nNeighbors[initialNode] + 1)); graph.neighbors[initialNode][graph.nNeighbors[initialNode]] = finalNode; graph.neighbors[finalNode] = realloc(graph.neighbors[finalNode], sizeof(int) * (graph.nNeighbors[finalNode] + 1)); graph.neighbors[finalNode][graph.nNeighbors[finalNode]] = initialNode; graph.nodesInSearch[initialNode] = realloc(graph.nodesInSearch[initialNode], sizeof(int) * (graph.nNeighbors[initialNode] + 1)); graph.nodesInSearch[initialNode][graph.nNeighbors[initialNode]] = 0; graph.nodesInSearch[finalNode] = realloc(graph.nodesInSearch[finalNode], sizeof(int) * (graph.nNeighbors[finalNode] + 1)); graph.nodesInSearch[finalNode][graph.nNeighbors[finalNode]] = 0; graph.nNeighbors[finalNode]++; graph.nNeighbors[initialNode]++; } trash = scanf(" %d", &nCritAreas); results = (int *) malloc(sizeof(int) * nCritAreas); criticPoints = (int **) malloc (sizeof(int *) * nCritAreas); nCriticPoints = (int *) malloc(sizeof(int) * nCritAreas); for(i = 0; i < nCritAreas; i++) { trash = scanf(" %d", &nCritPoints); criticPoints[i] = (int *) malloc(sizeof(int) * nCritPoints); nCriticPoints[i] = nCritPoints; for(j = 0; j < nCritPoints; j++) { trash = scanf( " %d", &criticPoint); criticPoints[i][j] = criticPoint; } } for (k = 0; k < nCritAreas; k++) { results[k] = INT_MAX; for (i = 0; i < nCriticPoints[k]; i++) { for (j = i+1; j < nCriticPoints[k]; j++) { trash = 0; queueReset(); trash = fordFulkerson(criticPoints[k][i], criticPoints[k][j]); results[k] = results[k] < trash ? results[k] : trash; } } } for (i = 0; i < nCritAreas; i++) { printf("%d\n", results[i]); } /* Frees */ for (i=0; i<graph.nNodes; i++) { free(graph.neighbors[i]); free(graph.nodesInSearch[i]); } free(graph.neighbors); free(graph.nNeighbors); free(graph.nodesInSearch); free(parent); free(visited); queueFree(); free(results); for (i = 0; i < nCritAreas; i++) { free(criticPoints[i]); } free(criticPoints); free(nCriticPoints); return 0; }
int serverMain(void) { int rc, signal; pthread_t thread_listen, thread_answer; running = 1; signal = SIGTERM; rc = EX_SOFTWARE; if (!sqlite3_threadsafe()) { fprintf(stderr, "thread-safe sqlite3 required\n"); goto error0; } if (pthreadInit()) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error0; } if ((service_addr = socketAddressNew("0.0.0.0", port)) == NULL) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error1; } if ((service = socketOpen(service_addr, 0)) == NULL) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error2; } if (socketSetReuse(service, 1)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error2; } if (socketBind(service, &service->address)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error2; } if (serverSignalsInit(&signals)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error3; } if (queueInit(&queries_unused)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error4; } if (queueInit(&queries_waiting)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error5; } if (sqlite3_open(database_path, &db) != SQLITE_OK) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error6; } if (create_database(db)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error7; } if (sqlite3_prepare_v2(db, SQL_SELECT_ONE, -1, &db_select_one, NULL) != SQLITE_OK) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error7; } if (0 < debug) syslog(LOG_DEBUG, "sql=\"%s\"", sqlite3_sql(db_select_one)); if (pthread_create(&thread_answer, NULL, answer_thread, NULL)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error8; } if (pthread_create(&thread_listen, NULL, listen_thread, NULL)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error9; } syslog(LOG_INFO, "ready"); signal = serverSignalsLoop(&signals); syslog(LOG_INFO, "signal %d, terminating process", signal); running = 0; rc = EXIT_SUCCESS; (void) pthread_cancel(thread_answer); (void) pthread_join(thread_answer, NULL); error9: (void) pthread_cancel(thread_listen); (void) pthread_join(thread_listen, NULL); error8: sqlite3_finalize(db_select_one); error7: sqlite3_close(db); error6: queueFini(&queries_waiting); error5: queueFini(&queries_unused); error4: serverSignalsFini(&signals); error3: socketClose(service); error2: free(service_addr); error1: pthreadFini(); error0: syslog(LOG_INFO, "signal %d, terminated", signal); return rc; }
// **************************************************************** int main() { /* reset number generator seed */ srand(time(NULL) + getpid()); //srand(0); // to get the same sequence /* initialize the price and it's mutex */ currentPriceX10 = 1000; price_mut = malloc (sizeof(pthread_mutex_t)); pthread_mutex_init(price_mut,NULL); slimit = signalInit(); lim = signalInit(); /* Open the log file for writing */ log_file = fopen("logfile.txt","w+"); /* * Initialize the array that we will use in order to log the type of each * of the order that are received by the system. * It is used only to by the cancel thread to find where each order has gone. */ saves.mut = malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(saves.mut,NULL); saves.archive = calloc(INT_MAX,sizeof(char)); if(saves.archive == NULL) perror( "Not enough memory" ); /* Start the time for timestamps */ gettimeofday (&startwtime, NULL); /* Create all the thread variables */ pthread_t prod, cons, cons2, market, lim_thread, stop_thread, slim_thread, cancel; /* Initialize the incoming order queue */ queue *q = queueInit(0); /* Initialize the buy and sell market queues. */ msq = queueInit(0); mbq = queueInit(0); /* Initialize the buy and sell limit order queues */ lsq = queueInit(ASC); lbq = queueInit(DESC); /* Initialize the buy and sell stop order queues */ ssq = queueInit(ASC); sbq = queueInit(DESC); /* Initialize the buy and sell stop limit order queues */ tsq = queueInit(ASC); tbq = queueInit(DESC); /* Initialize the cancel queue */ cq = queueInit(0); printf(" buffer |market sell|market buy|limit sell|limit buy |stop sell | stop buy |slimit sell|slimit buy | current price"); printf("\n\n"); /* Create and launch all the appropriate threads */ pthread_create(&prod, NULL, Prod, q); pthread_create(&cons, NULL, Cons, q); pthread_create(&cons2, NULL, Cons, q); pthread_create(&lim_thread, NULL, limitWorker, NULL); pthread_create(&market, NULL, marketWorker, NULL); pthread_create(&stop_thread, NULL, stopWorker, NULL); pthread_create(&slim_thread, NULL, stoplimitWorker, NULL); pthread_create(&cancel, NULL, cancelWorker, NULL); /* Join the producer thread. I actually do not expect it to ever terminate */ pthread_join(prod, NULL); pthread_exit(NULL); }
int main(int argc, char *argv[]) { // Define basic variables. int input; productList *products; Queue *q; // Allocate memory for pointers. products = newProductList(); q = newQueue(); // Load product-price data store and assert that it succeeded. if(loadProductList(products, "priceList.csv")!=0) { wait(); exit(-1); } queueInit(q); // Initialize queue. setAppTitle("SUPER MARKET COUNTER"); showSplash("splash.txt"); getch(); // Loops the menu till user chooses to exit. do { // Declare menu options. char mainMenu[][16]={"Arrive", "Process", "Print", "Front", "Rear", "Length", "Exit"}; // Display menu and receive user input. input = showMenu("Main Menu", mainMenu, 7); // Choose a function based on user input. switch(input) { case 1: qArrive(q, products); break; case 2: qProcess(q); break; case 3: qPrint(q); break; case 4: qFront(q); break; case 5: qRear(q); break; case 6: qLength(q); break; case 7: qExit(q, products); break; default: printf("Invalid Menu Option. Try again!"); wait(); continue; }; }while(1); return 0; }
/*----------------------------------------------------------------------------*/ static enum result canInit(void *object, const void *configBase) { const struct CanConfig * const config = configBase; const struct CanBaseConfig baseConfig = { .channel = config->channel, .rx = config->rx, .tx = config->tx }; struct Can * const interface = object; enum result res; /* Call base class constructor */ if ((res = CanBase->init(object, &baseConfig)) != E_OK) return res; interface->base.handler = interruptHandler; interface->callback = 0; interface->timer = config->timer; interface->mode = MODE_LISTENER; const size_t poolSize = config->rxBuffers + config->txBuffers; res = queueInit(&interface->pool, sizeof(struct CanMessage *), poolSize); if (res != E_OK) return res; res = queueInit(&interface->rxQueue, sizeof(struct CanMessage *), config->rxBuffers); if (res != E_OK) return res; res = queueInit(&interface->txQueue, sizeof(struct CanMessage *), config->txBuffers); if (res != E_OK) return res; interface->poolBuffer = malloc(sizeof(struct CanStandardMessage) * poolSize); struct CanStandardMessage *message = interface->poolBuffer; for (size_t index = 0; index < poolSize; ++index) { queuePush(&interface->pool, &message); ++message; } LPC_CAN_Type * const reg = interface->base.reg; reg->MOD = MOD_RM; /* Reset CAN */ reg->IER = 0; /* Disable Receive Interrupt */ reg->GSR = 0; /* Reset error counter */ interface->rate = config->rate; reg->BTR = calcBusTimings(interface, interface->rate); /* Disable Reset mode and activate Listen Only mode */ reg->MOD = MOD_LOM; LPC_CANAF->AFMR = AFMR_AccBP; //FIXME #ifdef CONFIG_CAN_PM if ((res = pmRegister(interface, powerStateHandler)) != E_OK) return res; #endif irqSetPriority(interface->base.irq, config->priority); /* Enable interrupts on message reception and bus error */ reg->IER = IER_RIE | IER_BEIE; return E_OK; } /*----------------------------------------------------------------------------*/ static void canDeinit(void *object) { struct Can * const interface = object; LPC_CAN_Type * const reg = interface->base.reg; /* Disable all interrupts */ reg->IER = 0; #ifdef CONFIG_CAN_PM pmUnregister(interface); #endif queueDeinit(&interface->txQueue); queueDeinit(&interface->rxQueue); CanBase->deinit(interface); } /*----------------------------------------------------------------------------*/ static enum result canCallback(void *object, void (*callback)(void *), void *argument) { struct Can * const interface = object; interface->callbackArgument = argument; interface->callback = callback; return E_OK; } /*----------------------------------------------------------------------------*/ static enum result canGet(void *object, enum ifOption option, void *data) { struct Can * const interface = object; switch (option) { case IF_AVAILABLE: *(size_t *)data = queueSize(&interface->rxQueue); return E_OK; case IF_PENDING: *(size_t *)data = queueSize(&interface->txQueue); return E_OK; case IF_RATE: *(uint32_t *)data = interface->rate; return E_OK; default: return E_INVALID; } } /*----------------------------------------------------------------------------*/ static enum result canSet(void *object, enum ifOption option, const void *data) { struct Can * const interface = object; LPC_CAN_Type * const reg = interface->base.reg; switch ((enum canOption)option) { case IF_CAN_ACTIVE: changeMode(interface, MODE_ACTIVE); return E_OK; case IF_CAN_LISTENER: changeMode(interface, MODE_LISTENER); return E_OK; case IF_CAN_LOOPBACK: changeMode(interface, MODE_LOOPBACK); return E_OK; default: break; } switch (option) { case IF_RATE: { const uint32_t rate = *(const uint32_t *)data; interface->rate = rate; reg->MOD |= MOD_RM; /* Enable Reset mode */ reg->BTR = calcBusTimings(interface, rate); reg->MOD &= ~MOD_RM; return E_OK; } default: return E_INVALID; } } /*----------------------------------------------------------------------------*/ static size_t canRead(void *object, void *buffer, size_t length) { assert(length % sizeof(struct CanStandardMessage) == 0); struct Can * const interface = object; struct CanStandardMessage *output = buffer; size_t read = 0; while (read < length && !queueEmpty(&interface->rxQueue)) { struct CanMessage *input; const irqState state = irqSave(); queuePop(&interface->rxQueue, &input); memcpy(output, input, sizeof(*output)); queuePush(&interface->pool, &input); irqRestore(state); read += sizeof(*output); ++output; } return read; }