Beispiel #1
0
void TestFifo::testWrappingReadWrite(void) {
    Fifo fifo(BUFFER_SIZE);

    u_int32_t value1[SIZE];
    u_int32_t value2[SIZE];

    for(size_t i=0;i<SIZE;++i)
        value1[i] = rand();

    pthread_t reader, writer;
    fifo_test_info_t read_info = {
        &fifo,
        value2,
    };
    fifo_test_info_t write_info = {
        &fifo,
        value1,
    };

    pthread_create(&reader,NULL,readFifo,&read_info);
    pthread_create(&writer,NULL,writeFifo,&write_info);

    pthread_join(writer,NULL);
    pthread_join(reader,NULL);

    for(size_t i=0;i<SIZE;++i)
        CPPUNIT_ASSERT_EQUAL(value1[i],value2[i]);
}
Beispiel #2
0
static int _stm32_qspi_poll(struct stm32_qspi_priv *priv,
			    const struct spi_mem_op *op)
{
	void (*fifo)(u8 *val, void __iomem *addr);
	u32 len = op->data.nbytes, sr;
	u8 *buf;
	int ret;

	if (op->data.dir == SPI_MEM_DATA_IN) {
		fifo = _stm32_qspi_read_fifo;
		buf = op->data.buf.in;

	} else {
		fifo = _stm32_qspi_write_fifo;
		buf = (u8 *)op->data.buf.out;
	}

	while (len--) {
		ret = readl_poll_timeout(&priv->regs->sr, sr,
					 sr & STM32_QSPI_SR_FTF,
					 STM32_QSPI_FIFO_TIMEOUT_US);
		if (ret) {
			pr_err("fifo timeout (len:%d stat:%#x)\n", len, sr);
			return ret;
		}

		fifo(buf++, &priv->regs->dr);
	}

	return 0;
}
Beispiel #3
0
void
Allocate::allocate( PortInfo &a, PortInfo &b, void *data )
{
   (void) data;

   FIFO *fifo( nullptr );
   auto &func_map( a.const_map[ Type::Heap ] );
   auto test_func( (*func_map)[ false ] );

   if( a.existing_buffer != nullptr )
   {
      fifo = test_func( a.nitems,
                        a.start_index,
                        a.existing_buffer );
   }
   else
   {
      /** if fixed buffer size, use that, else use INITIAL_ALLOC_SIZE **/
      const auto alloc_size( 
         a.fixed_buffer_size != 0 ? a.fixed_buffer_size : INITIAL_ALLOC_SIZE 
      );
      fifo = test_func( alloc_size            /* items */,
                        ALLOC_ALIGN_WIDTH     /* align */,
                        nullptr );
   }
   initialize( &a, &b, fifo );
   return;
}
int main(int argc, char** argv) {
    int i;	
    int *arr;
    int access_mem_count;
    int seed;

    if(argc<3) {
    	fprintf(stderr,"usage: %s [access_mem_count] [seed]\n",argv[0]);
    	exit(-1);
    }

    access_mem_count=atoi(argv[1]);
    seed=atoi(argv[2]);

    if(access_mem_count<100||access_mem_count>1000000) {
    	fprintf(stderr,"First parameter is wrong range\n");
    	exit(-1);
    }

    arr=(int*)malloc(sizeof(int)*access_mem_count);

	arr = genAddr(access_mem_count, seed);
        
    printf("FIFO: %d\n",fifo(arr,access_mem_count));
    printf("LRU: %d\n",lru(arr,access_mem_count));
    /*
    for(i = 0; i < access_mem_count; i++)
		printf("%dst addr value : %d\n", i, arr[i]);
	*/
	return 0;
}
Beispiel #5
0
int main()
{
int i,ch;
printf("\nEnter total number of pages:");
scanf("%d",&n);
printf("\nEnter sequence:");
for(i=0;i<n;i++) //accepting sequence
scanf("%d",&pg[i]);
do
{
printf("\n\tMENU\n");
printf("\n1)FIFO");
printf("\n2)OPTIMAL");
printf("\n3)LRU");
printf("\n4)Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: fifo();
break;

case 2: optimal();
break;

case 3: lru();
break;

}
}while(ch!=4);
getchar();
}
Beispiel #6
0
int main(int argc, char**argv)
{
	int produce = argc>1 ? atoi(argv[1]) : 10000000;
	FIFO<int> fifo(100000);
	Producer producer(produce, fifo);
	Consumer consumer(10000, fifo);
	active::run();
	std::cout << consumer.get();
}
Beispiel #7
0
void TestFifo::testSingleReadWrite(void) {
    Fifo fifo(BUFFER_SIZE);
    u_int32_t value1 = DAT_MAGIC;
    u_int32_t value2 = 0;

    CPPUNIT_ASSERT(sizeof(value1) < BUFFER_SIZE);
    CPPUNIT_ASSERT_EQUAL(sizeof(value1),sizeof(value2));
    CPPUNIT_ASSERT_EQUAL(sizeof(value1),fifo.write(&value1,sizeof(value1)));
    CPPUNIT_ASSERT_EQUAL(sizeof(value2),fifo.read(&value2,sizeof(value2)));
    CPPUNIT_ASSERT_EQUAL(value1,value2);
}
Beispiel #8
0
//main
int main(void){
	int i = 0;
	 for(i=1;i<=7;i++){
	 	fifo(i);
	 }
	 for(i=1;i<=7;i++){
	 	lru(i);
	 }
	for(i=1;i<=7;i++){
		opt(i);
	}


}
	//called when client want to read any page into memory, it decides on strategy which will be
	//used at the time of page replacement.
	RC pinPage (BM_BufferPool *const bm, BM_PageHandle *const page, const PageNumber pageNum){
	if(bm!=NULL){
		
			if(bm->strategy==RS_FIFO){
				 fifo(bm,page,pageNum);//calls FIFO.
				
			}else if(bm->strategy==RS_LRU){
				lru(bm,page,pageNum);//calls LRU
			}
				return RC_OK;
			}else{
				RC_message="Buffer is not initialized ";
				return RC_BUFFER_NOT_INITIALIZED;
			}
	}
Beispiel #10
0
////////////////////////////////////////
////////////////////////////////////////BFS
////////////////////////////////////////
void Graph::bfs(int s)
{
    std::vector<int> pai(this->n);       // Vetor que armazenará os pais de todos os vértices. Por default, o pai será 0 se não for alcançado
    std::vector<int> level(this->n,-1); // Vetor que armazenará os níveis de todos os vértices. Caso não seja alcançado, o nível será -1
    std::vector<int> markVec(this->n); // Vetor de marcação. Se um vértice for adicionado na fila, ele é marcado
    std::vector<int> fifo(this->n);   // Fila que armazenará os vértices descobertos e que ainda não foram explorados
    int v;                           // Vértice que será explorado
    int degV;                       // Grau do vértice v
    int begin = 0;                 // Posição do primeiro que entrou na fila
    int end = 0;                  // Posição onde será colocado o próximo a entrar na fila
    pai[s-1] = -1;
    level[s-1] = 0;
    markVec[s-1] = 1;
    fifo[end++] = s;

    while(begin!=end)
    {
        v = fifo[begin++];
        degV = vDeg[v-1];

        std::vector<int> &neigh = this->getAdj(v);  //Referência a um vetor, ou seja, não há cópia

        for(int i = 0; i<degV; i++)
        {
            if(markVec[neigh[i]-1]==0)
            {
                markVec[neigh[i]-1] = 1;
                fifo[end++] = neigh[i];
                pai[neigh[i]-1] = v;
                level[neigh[i]-1] = level[v-1] + 1;
            }
        }
    }
    // Escrevendo em arquivo
    char st [50] = "bfs_";
    char ss [11] = {0};
    std::sprintf(ss, "%d", s);
    strcat(st, ss);
    strcat(st, "_");
    std::ofstream outfile;
    outfile.open(strcat(st,this->path), std::ios::out);

    for(int i = 0; i<this->n; i++)
    {
        outfile << i+1 << ", pai: " <<pai[i] << ", nivel: " << level[i] << std::endl;
    }
}
Beispiel #11
0
void fileTransferThread::addFilesToSend() {
	QStringList flist = QFileDialog::getOpenFileNames( static_cast<QWidget*>(parent()), tr("Choose files to send"), QDir::homePath() );

	if( flist.count() ) {
		QStringListIterator it(flist);
		while(it.hasNext()) {
			QString f=it.next();
			QFileInfo fifo(f);
			QStringList info;
			info<<fifo.fileName()<<""<<""<<""<<""<<QString("%L1 kB").arg( (float)qRound( ( (float)fifo.size()/1024 )*10 )/10 )<<fifo.absolutePath()<<QString("%1").arg( fifo.size() );
			fc++;
			allSize+=fifo.size();
			QTreeWidgetItem *item = new QTreeWidgetItem(info);
			fileMap<<item;
			emit addListItem(item);
		}
		emit updateFilesData(fc, allSize);
	}
}
Beispiel #12
0
////////////////////////////////////////
////////////////////////////////////////FindCC
////////////////////////////////////////
void Graph::findCC()
{
    std::vector<int> markVec(this->n);
    std::vector<int> fifo (this->n);
    int begin = 0;
    int end = 0;
    int degV;
    int v;
    int count = 0;
    int m = 1; //vértice na maior componente de menor índice
    int tam = 0; //tamanho da maior componente
    int tamP; // tamanho parcial, a ser comparado com o tamanho da maior componente analisada até o momento

    for (int i =0; i < this->n ;i++)
    {
        if (markVec[i]==0)
        {
            tamP = 1;
            markVec[i] = ++count;
            fifo[end++] = i+1;
            while (begin!=end)
            {
                v = fifo[begin++];
                degV = vDeg[v-1];
                std::vector<int> &neigh = this->getAdj(v);
                for (int j = 0; j < degV ; j++)
                {
                    if(markVec[neigh[j]-1]==0)
                    {
                        markVec[neigh[j]-1] = count;
                        fifo[end++] = neigh[j];
                        tamP++;
                    }
                }
            }
            if (tamP>tam) {m = i + 1; tam = tamP;}
        }
    }
    this->cc = count;
    this->vMax = m;
    this->tamCC = tam;
}
Beispiel #13
0
int main(int argc, char** argv)
{
  PArray* array = create();
  seed();

  if (argc > 1)
  {
    if (strcmp(argv[1], "fifo") == 0)
    {
      fifo(array);
      execute(array);
    }
    else if (strcmp(argv[1], "shortestTime") == 0)
    {
      // Initialize the array, fifo is fine here
      fifo(array);
      shortestTime(array);
      execute(array);
    }
    else if (strcmp(argv[1], "priority") == 0)
    {
      // Initialize the array, fifo is fine here
      fifo(array);
      priority(array);
      execute(array);
    }
    else if (strcmp(argv[1], "fifoRoundRobin") == 0)
    {
      fifo(array);
      executeRoundRobin(array);
    }
    else if (strcmp(argv[1], "priorityRoundRobin") == 0)
    {
      // Initialize the array, fifo is fine here
      fifo(array);
      priority(array);
      executeRoundRobin(array);
    }
  }
  else
  {
    fifo(array);
    execute(array);
  }

  return 0;
}
Beispiel #14
0
RC pinPage (BM_BufferPool *const bm, BM_PageHandle *const page,const PageNumber pageNum)
{
PageFrames *findpage;
if(bm==NULL){RC_message= "pinPage"; return RC_BUFFER_NOT_INIT;}	

if(pageNum==NO_PAGE){RC_message= "pinPage"; return RC_PAGE_NOT_INIT;}		

RC msg;
switch(bm->strategy)
{
case RS_FIFO:
return fifo(bm,page,pageNum);
break;
case RS_LRU:
return LRU(bm,page,pageNum);
break;
default:
break;
}

return RC_OK;
}
Beispiel #15
0
void 
Allocate::allocate( PortInfo &a, PortInfo &b, void *data )
{
   FIFO *fifo( nullptr );
   instr_map_t * const func_map( a.const_map[ Type::Heap ] );
   auto test_func( (*func_map)[ false ] );
   
   if( a.existing_buffer != nullptr )
   {
      fifo = test_func( a.nitems, 
                        a.start_index,
                        a.existing_buffer );
   }
   else
   {
      fifo = test_func( INITIAL_ALLOC_SIZE    /* items */, 
                        ALLOC_ALIGN_WIDTH     /* align */, 
                        nullptr );
   }
   initialize( &a, &b, fifo );
   return;
}
Beispiel #16
0
void
stdalloc::run()
{
   auto alloc_func = [&]( PortInfo &a,
                          PortInfo &b,
                          void *data )
   {
      (void) data;

      assert( a.type == b.type );
      /** assume everyone needs a heap for the moment to get working **/
      instr_map_t *func_map( a.const_map[ Type::Heap ] );
      FIFO *fifo( nullptr );
      auto test_func( (*func_map)[ false ] );
      /** check and see if a has a defined allocation **/
      if( a.existing_buffer != nullptr )
      {
         fifo = test_func( a.nitems,
                           a.start_index,
                           a.existing_buffer );
      }
      else
      {
         /** check for pre-existing alloc size for test purposes **/
         fifo = test_func( a.fixed_buffer_size != 0 ?
                              a.fixed_buffer_size : 4 /** size **/,
                           16 /** align **/,
                           nullptr /* data struct **/);
      }
      assert( fifo != nullptr );
      (this)->initialize( &a, &b, fifo );
   };
   auto &container( (this)->source_kernels.acquire() );
   GraphTools::BFS( container, alloc_func );
   (this)->source_kernels.release();
   (this)->setReady();
   return;
}
Beispiel #17
0
int main() 
{
  int refString[100];
  srand(time(NULL));

  refString[1] = rand()%15;
  for(int i=1; i<100; i++) {
    refString[i] = rand()%15;
    while(refString[i] == refString[i-1]) {
      refString[i] = rand()%15;
    }
  }

  int t1[16];
  zeroTable(t1,16);

  printf("FIFO:\n");
  int one;

  for(int i=1; i<17; i++) {
    zeroTable(t1,16);
    one = fifo(t1, i, refString, 100);
    printf("%d\n", one);
  }

  printf("\nLRU:\n");
  zeroTable(t1,16);
  one = LRU(t1, 1, refString, 100);

  for(int i=1; i<17; i++) {
    zeroTable(t1,16);
    one = LRU(t1, i, refString, 100);
    printf("%d\n", one);
  }

}
Beispiel #18
0
//Devuelve el numero de marco para asignar o -1 si no había disponibles
int marco_libre(int pid) {

	log_info(logger, "Se busca un marco libre para asignar");

	pid_matchear = pid;

	int paginaNuevoProceso = pagina_matchear;

	if (marcos_libres() == 0) {
		//Si no hay marcos disponibles
		log_info(logger, "No hay marcos libres para asignar");

		if (tiene_marcos_asignados(pid)) {

			loggearInfo(
					"El proceso ya tiene marcos asignados, se swappea alguno existente");

			//Swappea uno que ya tiene

			if (es_fifo()) {
				return fifo();
			}

			if (es_lru()) {
				return lru();
			}

			int marco = clock_m();
			pagina_matchear = paginaNuevoProceso;

			t_item * itemParaMeter = list_find(tabla_paginas,
					coincide_pid_y_pagina);

			list_replace(cola_llegada, posicionVictima, itemParaMeter);

			loggearInfo("Se remplaza la victima con el nuevo elemento");

			return marco;

		} else {
			loggearInfo("No hay marcos disponibles para asignar");
			//No le puedo dar ninguno, se aborta
			return -1;
		}

	} else {

		//Hay marcos libres
		loggearInfo("Hay marcos disponibles para asignar");

		int cantidad_maxima_marcos_proceso = config_get_int_value(memoriaConfig,
				"MAXIMO_MARCOS_POR_PROCESO");

		if (marcos_asignados(pid) < cantidad_maxima_marcos_proceso) {

			loggearInfo(
					"El proceso tiene menos marcos que la cantidad maxima, se le da uno nuevo");

			//Le doy un marco nuevo

			int marco = marco_disponible();

			if (es_clock_modificado()) {

				//Si es clockModificado me fijo si no tiene presentes,
				//significa que este que tengo acá en pid_matchear y pagina_matchear
				//es el único elemento presente y pasa a ser puntero

				t_item * elementoParaHacerPuntero;

				bool algunoPresente = list_any_satisfy(tabla_paginas,
						coincide_pid_y_esta_presente);

				if (!algunoPresente) {

					elementoParaHacerPuntero = list_find(tabla_paginas,
							coincide_pid_y_pagina);

					elementoParaHacerPuntero->puntero = true;

				}

			}

			return marco;

		} else {

			loggearInfo(
					"El proceso ya tiene la cantidad maxima de marcos, se swappea uno existente");
			//Tiene el maximo y necesita swappear uno existente

			if (es_fifo()) {
				return fifo();
			}

			if (es_lru()) {
				return lru();
			}

			int marco = clock_m();
			pagina_matchear = paginaNuevoProceso;

			t_item * itemParaMeter = list_find(tabla_paginas,
					coincide_pid_y_pagina);

			itemParaMeter->uso = true;

			list_replace(cola_llegada, posicionVictima, itemParaMeter);

			loggearInfo("Se remplaza la victima con el nuevo elemento");

			return marco;

		}

	}
}
int main()
{
	int notRST	= TRUE;
	int LDCK	= FALSE;
	int Dbus [4]= {FALSE, FALSE, FALSE, FALSE};
	/*почему в массиве Dbus 4 элементов? Да потому что если сделать их три, то notEMPTY тоже меняет значение
	я абсолютно не понимаю причину этого. Можете конечно поэксперементировать, но не думаю что у вас что-то выйдет.*/
	int UNCK	= FALSE;
	int Qbus [4]= {FALSE, FALSE, FALSE, FALSE};
	//почему снова 4 элементов? Да на всякий случай! см. комментарий выше
	int notEMPTY= TRUE;
	int notFULL = TRUE;

	//массив, который указывает на расположение переменных с очередью
	int queue [16] [3];

	//две переменные, в которых будет храниться номер, на котором остановилась очередь вывода и ввода
	int loadNum = 0;
	int unloadNum = 0;
	


	int notRSTgraph	[30];
	int LDCKgraph	[30];
	int Dgraph  [4] [30];
	int UNCKgraph	[30];
	int Qgraph  [4] [30];
	int notEMPTYgraph[30];
	int notFULLgraph[30];



	



	/********************************************
	*****         рисование графиков         ****
	********************************************/
	
	for (int period = 0; TRUE; period++) {

	system (cleanScreen);

		//выполняется главная функция
		fifo (&Dbus, LDCK, &Qbus, UNCK, &queue, &loadNum, &unloadNum);


	printf("%s%i", "     notRST ", notRST);	drawGraph(notRST, period, &notRSTgraph);
	printf("%s%i", "       LDCK ", LDCK);	drawGraph(LDCK, period, &LDCKgraph);
	printf("%s%i", "         D0 ", Dbus[0]);	drawGraph(Dbus[0], period, &Dgraph[0]);
	printf("%s%i", "         D1 ", Dbus[1]);	drawGraph(Dbus[1], period, &Dgraph[1]);
	printf("%s%i", "         D2 ", Dbus[2]);	drawGraph(Dbus[2], period, &Dgraph[2]);
	printf("%s%i", "         D3 ", Dbus[3]);	drawGraph(Dbus[3], period, &Dgraph[3]);
	printf("%s%i", "       UNCK ", UNCK);	drawGraph(UNCK, period, &UNCKgraph);
	printf("%s%i", "         Q0 ", Qbus[0]);	drawGraph(Qbus[0], period, &Qgraph[0]);
	printf("%s%i", "         Q1 ", Qbus[1]);	drawGraph(Qbus[1], period, &Qgraph[1]);
	printf("%s%i", "         Q2 ", Qbus[2]);	drawGraph(Qbus[2], period, &Qgraph[2]);
	printf("%s%i", "         Q3 ", Qbus[3]);	drawGraph(Qbus[3], period, &Qgraph[3]);
	printf("%s%i", "   notEMPTY ", notEMPTY);	drawGraph(notEMPTY, period, &notEMPTYgraph);
	printf("%s%i", "    notFULL ", notFULL);	drawGraph(notFULL, period, &notFULLgraph);
	//если хочется посмотреть состояние счетчиков, то раскомметируйте строчку ниже.
	//printf("%s%i%s%i\n", "loadNum = ", loadNum, "unloadNum = ", unloadNum);
	printf("\n%s\n", "for next period- enter \"-\"");
	

		char inpt [10];
		scanf ("%s", inpt);
		if ( inpt [0] == 'q') break;

		for (int c = 0; inpt[c] != '\0'; c++) {
			if ( inpt [c] == '-') ;
			if ( inpt [c] == '0') Dbus[0] = !Dbus[0];
			if ( inpt [c] == '1') Dbus[1] = !Dbus[1];
			if ( inpt [c] == '2') Dbus[2] = !Dbus[2];
			if ( inpt [c] == '3') Dbus[3] = !Dbus[3];
			if ( inpt [c] == 'l') LDCK = !LDCK;
			if ( inpt [c] == 'u') UNCK = !UNCK;
			if ( inpt [c] == 'r') {
					notRST = !notRST;
					loadNum = 1;
					unloadNum = 0;
					notEMPTY = FALSE;
					notFULL = TRUE;
			}
		}
	}

	return 0;
}
RC pinPage (BM_BufferPool *const bm, BM_PageHandle *const page, 
	    const PageNumber pageNum)
{
	Data_Structure *ds = (Data_Structure *)bm->mgmtData;
	
	if(ds[0].pagenum == -1)
	{
		//printf("\nINSIDE ds[0]->pagenum == -1\n");
		
		SM_FileHandle fh;
		openPageFile (bm->pageFile, &fh);
		ds[0].data = (SM_PageHandle) malloc(PAGE_SIZE);
		ensureCapacity(pageNum,&fh);
		readBlock(pageNum, &fh, ds[0].data);
		ds[0].pagenum = pageNum;
		ds[0].fixedcnt++;
		rear = 0;
		hit = 0;
		ds[0].hitnum = hit;	
		ds[0].numRef = 0;	
		page->pageNum = pageNum;
		page->data = ds[0].data;
		
		/*	
		printf("\nPinPage function buffer");
		int i;
		for(i=0;i<bufferSize; i++)
		{
			printf("\nPagenum: %d fixedcnt: %d dirty: %d",ds[i].pagenum,ds[i].fixedcnt,ds[i].dirtybit);	
		}*/
		
		return RC_OK;		
	}
	else
	{	
		//printf("\nINSIDE front != NULL\n");
		int i,check = 0;
		
		for(i=0;i<bufferSize;i++)
		{
			if(ds[i].pagenum != -1)
			{	
				if(ds[i].pagenum == pageNum)  //if Page already in memory
				{
					ds[i].fixedcnt++;
					check = 1;
					hit++;
					if(bm->strategy == RS_LRU)	
						ds[i].hitnum = hit;
					else if(bm->strategy == RS_CLOCK)		//if bm-> strategy is RS_CLOCK storing the USED bit in hitnum.
						ds[i].hitnum = 1;
					else if(bm->strategy == RS_LFU)
						{
						ds[i].numRef++;
						//printf("Page %d referenced again \n", pageNum);
						//rear = rear + 2;
						//printf(" rear : %d \n", rear);
						}
					
					
					page->pageNum = pageNum;
					page->data = ds[i].data;

					clockptr++;
					
					break;
				}				
			}
			else	//Condition when the buffer has space to add a page
			{
				SM_FileHandle fh;
				openPageFile (bm->pageFile, &fh);
				ds[i].data = (SM_PageHandle) malloc(PAGE_SIZE);
				readBlock(pageNum, &fh, ds[i].data);
				ds[i].pagenum = pageNum;
				ds[i].fixedcnt = 1;
				ds[i].numRef = 0;
				rear++;	
				hit++;
				if(bm->strategy == RS_LRU)
					ds[i].hitnum = hit;				
				else if(bm->strategy == RS_CLOCK)		//if bm-> strategy is RS_CLOCK storing the USED bit in hitnum.
					ds[i].hitnum = 1;
				
								
				page->pageNum = pageNum;
				page->data = ds[i].data;
				
				check = 1;
				break;
			}
		}//end of for
		
		if(check == 0)//Condition when the buffer is full and we need to use a replacement strategy.
		{
			Data_Structure *temp = (Data_Structure *)malloc(sizeof(Data_Structure));		
						
			SM_FileHandle fh;
			openPageFile (bm->pageFile, &fh);
			temp->data = (SM_PageHandle) malloc(PAGE_SIZE);
			readBlock(pageNum, &fh, temp->data);
			temp->pagenum = pageNum;
			temp->dirtybit = 0;		
			temp->fixedcnt = 1;
			temp->numRef = 0;
			rear++;
			hit++;
			//printf("HIT : %d \n", hit); //test by Rakesh
			if(bm->strategy == RS_LRU )
				temp->hitnum = hit;
			else if(bm->strategy == RS_CLOCK)			//if bm-> strategy is RS_CLOCK storing the USED bit in hitnum.
				temp->hitnum = 1;

			page->pageNum = pageNum;
			page->data = temp->data;			

			switch(bm->strategy)
			{			
				case RS_FIFO:	//printf("\n Inside FIFO switch.");
						fifo(bm,temp);
						break;
				case RS_LRU:	//printf("\n Inside LRU switch.");
						lru(bm,temp);  						
						break;
				case RS_CLOCK:	//printf("\n Inside CLOCK switch");
						clock(bm,temp);						
						break;
  				case RS_LFU:	//printf("\n Inside LFU switch");
  						LFU(bm,temp);
						break;
  				case RS_LRU_K:	printf("\n Inside LRU_K switch");
						break;
				default:
								printf("\nAlgorithm Not Implemented\n");
						break;
			}//end of switch
						
		}//end of if(check = 0)
		
		/*
		printf("\nPinPage function buffer");
		for(i=0;i<bufferSize;i++)
			printf("\nPagenum: %d fixedcnt: %d dirty: %d",ds[i].pagenum,ds[i].fixedcnt,ds[i].dirtybit);
		*/		
		return RC_OK;
	}//end of else	
}
Beispiel #21
0
void
dynalloc::run()
{
   auto alloc_func = [&]( PortInfo &a, PortInfo &b, void *data )
   {
      assert( a.type == b.type );
      /** assume everyone needs a heap for the moment to get working **/
      instr_map_t *func_map( a.const_map[ Type::Heap ] );
      FIFO *fifo( nullptr );
      auto test_func( (*func_map)[ false ] );
      /**
       * TODO, fix this one.
       */
      if( a.existing_buffer != nullptr )
      {
         fifo = test_func( a.nitems,
                           a.start_index,
                           a.existing_buffer );
      }
      else
      {
         fifo = test_func( 64 /* items */, 
                           16 /* align */, 
                           nullptr );
      }
      assert( fifo != nullptr );
      (this)->initialize( &a, &b, fifo );
   };

   /** BEGIN TEST DATA **/
   GraphTools::BFS( (this)->source_kernels,
                    alloc_func );
   
   (this)->setReady();
   std::map< std::size_t, int > size_map;
   
   /** 
    * make this a fixed quantity right now, if size > .75% at
    * montor interval three times or more then increase size.
    */

   auto mon_func = [&]( PortInfo &a, PortInfo &b, void *data ) -> void
   {
      const float ratio( 0.75 );
      const auto hash_val( dynalloc::hash( a, b ) );
      /** TODO, the values might wrap if no monitoring on **/
      const auto realized_ratio( a.getFIFO()->get_frac_write_blocked() );
      if( realized_ratio >= ratio )
      {
         const auto curr_count( size_map[ hash_val ]++ );
         if( curr_count  == 2 )
         {
            /** get initializer function **/
            auto * const buff_ptr( a.getFIFO() );
            const auto cap( buff_ptr->capacity() );
            buff_ptr->resize( cap * 2, 16, exit_alloc );
            size_map[ hash_val ] = 0;
         }
      }
      return;
   };
   /** start monitor loop **/
   while( ! exit_alloc )
   {
      /** monitor fifo's **/
      std::chrono::microseconds dura( 100 );
      std::this_thread::sleep_for( dura );
      GraphTools::BFS( (this)->source_kernels ,
                       mon_func );
   }
   return;
}
Beispiel #22
0
int main(int argc, char *argv[]) { return fifo(argc, argv); }
//TODO dynamically maintain all array sizes
int main(int argc, char** argv) {

	int fr_no=5, s=0;
	char rep_policy[20] = "FIFO";
	char logpath[1024] = "input.txt";

	for (s=1; s<argc; s++) {
		if (strcmp(argv[s], "-f")==0) {
			fr_no = atoi(argv[++s]);
		} else if (strcmp(argv[s], "-r")==0) {
			strcpy(rep_policy, argv[++s]);
		} else if (strcmp(argv[s], "-i")==0) {
			strcpy(logpath, argv[++s]);
		} else if (strcmp(argv[s], "-h")==0) {
			printf("help mode");
			serverOptions();
		} else {
			printf("\n\nNo Options Passed, ...\n");
		}
	}
	
	int i, j=0,nf=0;
	if(fr_no>0){
		nf=fr_no;
	}
	else{
		printf("Enter proper frame value\n");
		exit(0);
	}
	unsigned int input[16] ={0,1,2,3,0,1,2,3,0,1,2,3,4,5,6,7};//{1,2,3,4,1,2,5,1,2,3,4,5};
	count_page=0;
				//{ 1, 2, 3, 1, 1, 2, 4, 1, 3, 2, 1, 3 };// //TODO load the array size from file inputs
	
	//Reading from file
	FILE *f;
			char res[1024];
			f = fopen(logpath,"r");

			if (f == NULL) {perror ("Error opening file..Exiting...\n");exit(0);}
			else {
				fgets(res,1024,f);
				//puts(res);
				char* str=NULL;
				char delim[] = " ";
				str=strtok(res,delim);
					while(str!=NULL) {						
						input[i]=atoi(str);
						i++;
						count_page++;						
						str = strtok(NULL," ");
					}
			}
				printf("%d %s %s\n", fr_no, rep_policy, logpath);
	if (strcmp(rep_policy,"LRU-REF8")==0) {
		printf("Executing LRU-Ref8\n");
		pr1=lruRefBit(input, nf);
		pr2 = optim(input, nf);
		compare(rep_policy);
		return 0;
	}
	/*else if(==2){
	 optim(input,nf);
	 return 0;
	 }*/
	else if (strcmp(rep_policy,"LRU-STACK")==0) {
		printf("Executing LRU-STACK\n");
		pr1= lruStack(input, nf);
		pr2 = optim(input, nf);
		compare(rep_policy);
		return 0;
	} else if (strcmp(rep_policy,"LFU")==0) {
		printf("Executing LFU\n");
		pr1=lfu(input, nf);
		pr2 = optim(input, nf);
		compare(rep_policy);
		return 0;
	} else if (strcmp(rep_policy,"LRU-CLOCK")==0) {
		pr1 = lruref8bit(input,nf);
		pr2 = optim(input, nf);
		compare(rep_policy);
	} else {
		pr1 = fifo(input, nf);
		pr2 = optim(input, nf);
		compare(rep_policy);
		return 0;
	}
}
Beispiel #24
0
int main(int argc, char * argv[])
{
  int policy; /* replacement policy */
  int current;  /* current page accessed */
  FILE * fp; /* The file containing the page accesses */
  FILE * rp; /* output file */
  char filename[30]={""};
  const char * extension[] ={".fifo", ".lru", "new"};
  float num_accesses = 0.0; /* total number of page accesses */
  float page_faults = 0.0;
  unsigned victim = 0;  /* page to be replaced */
  
  /* Getting and checking the input from the command line */
  if(argc != 4)
  {
    printf("usage: pager policy size filename\n");
    exit(1);
  }
  
  policy = atoi(argv[1]);
  mem_size = atoi(argv[2]);
  
  if( policy < 0 || policy > 2)
  { 
    printf("policy must be 0, 1, or 2\n");
    exit(1);
  }
  
  if(mem_size <= 0 )
  {
    printf("Size must be a positive integer.\n");
    exit(1);
  }
  
  /* Allocate and initialize the memory */
  mem = (int *)calloc(mem_size, sizeof(int));
  if(!mem)
  {
    printf("Cannot allocate mem\n");
    exit(1);
  }
  
  /* open the memory access file */
  fp = fopen(argv[3], "r");
  if(!fp)
  {
    printf("Cannot open file %s\n", argv[3]);
    exit(1);
  }
  
  /* Create the output file */
  strcat(filename, argv[3]);
  strcat(filename,extension[policy]);
  rp = fopen(filename, "w");
  if(!rp)
  {
    printf("Cannot create file %s\n", filename);
    exit(1);
  }
  
  /* The main loop of the program */
  fscanf(fp,"%d", &current);
  while(!feof(fp))
  {
    num_accesses++;
    if(mem_check(current) == PAGEMISS)
      page_faults++;
    
    switch(policy)
    {
      case 0: if( IsFull())
	      {
		victim = fifo();
		mem[victim] = current;
	      }
	      else
		insert(current);
	      break;
	     
      case 1: if( IsFull())
	      {
		victim = lru();
		mem[victim] = current;
	      }
	      else
		insert(current);
	      break;
	      
      case 2: if( IsFull())
	      {
		victim = own();
		mem[victim] = current;
	      }
	      else
		insert(current);
	      break;
	      
	      
      default: printf("Unknown policy ... Exiting\n");
	       exit(1);
      
    }/* end switch-case */
    
    print_mem(rp);
    fscanf(fp,"%d", &current);

  }/* end while */
  fprintf(rp,"percentage of page faults = %f", page_faults/num_accesses);
  
  /* wrap-up */
  fclose(fp);
  fclose(rp);
  free(mem);
  
  return 1;

}
Beispiel #25
0
int Graph::diametro()
{
    // Uso de programação paralela com OpenMP
    int degV;
    int v;
    int diamP; // Armazena o diâmetro parcial. Cada thread vai ter sua variável diamP privada
    int begin = 0;
    int end = 0;
    int i = 0;

    /*
    *  Comandos do OpenMP utilizados:
    *  omp_get_max_threads(): retorna o número máximo de threads que você pode utilizar
    *  omp_set_num_threads(): define quantas threads você estará utilizando
    *  omp_get_thread_num() : retorna o número da thread atual
    *
    *  #pragma omp parallel for firstprivate(begin,end) private(i,degV,v,diamP) schedule(static)
    *  Paraleliza o for, e cada thread terá seus próprios atributos que estiverem definidos como
    *  privados. Firstprivate significa que eles serão inicializados com os valores previamente
    *  definidos. Schedule(static) significa que ele dividirá os intervalos do 'for' a princípio
    *  de maneira estática, ou seja, dividirá em pedaços de tamanhos parecidos.
    */

    std::vector<int> diametros(omp_get_max_threads()); // Cada thread terá direito a armazenar um diâmetro parcial
    omp_set_num_threads(omp_get_max_threads());

    #pragma omp parallel for firstprivate(begin,end) private(i,degV,v,diamP) schedule(static)

    for (i = 0; i < this->n;i++)
    {
        // Cada thread tem seus respectivos vetores
        std::vector<int> markVec(this->n);
        std::vector<int> level(this->n,-1);
        std::vector<int> fifo (this->n);

        diamP = 0;
        markVec[i] = i+1;
        level[i] = 0;
        fifo[end++] = i+1;
        while (begin!=end)
        {
            v = fifo[begin++];

            degV = vDeg[v-1];
            std::vector<int> &neigh = this->getAdj(v);

            for (int j = 0; j < degV ; j++)
            {
                if(markVec[neigh[j]-1]!=i+1)
                {
                    markVec[neigh[j]-1] = i+1;
                    fifo[end++] = neigh[j];
                    level[neigh[j]-1] = level[v-1] + 1;
                    diamP = level[neigh[j]-1];
                }

            }
        }

        if (diamP>diametros[omp_get_thread_num( )])
        {
            diametros[omp_get_thread_num( )] = diamP;
        }
        begin = 0; end = 0;
    }
    int diametro = diametros[0];

    for (int k = 1; k < omp_get_max_threads( ); k++)
    {
        if (diametros[k]>diametro)
        {
            diametro = diametros[k];
        }
    }
    return diametro;
}
Beispiel #26
0
int Graph::rComponents()
{
    std::priority_queue<double> heap;   // Fila de prioridade
    if(this->cc == 0) this->findCC();  // Caso o número de componentes conexas ainda não tenha sido determinado
    int count = this->cc;
    std::vector<std::list<int> > comp(count); // indice = i-ésima componente
    std::vector<int> markVec(this->n);
    std::vector<int> fifo (this->n);
    int begin = 0;
    int end = 0;
    int degV;
    int v;
    double factor;

    count = 0;
    for (int i =0; i < this->n ;i++)
    {
        if (markVec[i]==0)
        {
            markVec[i] = ++count;
            fifo[end++] = i+1;
            while (begin!=end)
            {
                v = fifo[begin++];
                comp[count-1].push_back(v);
                degV = vDeg[v-1];
                std::vector<int> &neigh = this->getAdj(v);

                for (int j = 0; j < degV ; j++)
                {
                    if(markVec[neigh[j]-1]==0)
                    {
                        markVec[neigh[j]-1] = count;
                        fifo[end++] = neigh[j];
                    }
                }
            }
            // MAGIC
            factor = ((double)count/(double)pow(10,ceil(log10(this->cc+1))));
            heap.push((double)comp[count-1].size()+ factor);
            // \MAGIC
            /*
            *  O código acima armazena na fila de prioridade o tamanho da componente conexa na parte
            *  inteira, e o índice que tal componente possui no vetor 'comp' na mantissa. Desta forma,
            *  quando quisermos pegar a maior, basta acessar o topo de tal fila (no caso de empate,
            *  será escolhida aquela componente de maior índice
            */
        }
    }

    char st [50] = "CC_";
    std::ofstream outfile;
    outfile.open(strcat(st,this->path), std::ios::out);

    double turn;
    int intTurn;
    outfile << "Number of Connected Components: " << this->cc << std::endl;
    while (!heap.empty())
    {
        // Magic
        turn = (heap.top()-floor(heap.top()))*pow(10,ceil(log10(this->cc+1)))-1;
        // \Magic
        /*
        *  O código acima apenas recupera o índice, que está guardado na mantissa do valor
        *  no topo da fila de prioridade. Note que, no caso de 10 componentes conexas, os
        *  valores nas mantissas vão de 1 até 10. Logo, precisamos de duas casas decimais
        *  para representar o valor (por isso existe o +1 dentro do log10). Como começa de
        *  1, o valor da mantissa deve ser decrescido de 1 para se tornar o índice do vetor
        *  'comp' de componentes conexas (por isso o -1)
        */
        intTurn = (int)(turn+0.5);
        /*
        *  Como turn é double, tivemos que usar desse artifício para transformá-lo para int.
        *  A representação de um número double pode ser feita de diferentes formas. Por exemplo,
        *  o número 35 pode ser representado como 34,999999 ou como 35,0000001. Ao fazermos um
        *  cast pra inteiro, ele trunca, tirando a parte decimal. Logo, o mesmo número em double,
        *  dependendo da forma como é representado, pode dar diferentes resultados em inteiro.
        *  Por isso adicionamos o termo +0.5, garantindo que o resultado final esteja entre o
        *  valor esperado turn e seu sucessor turn+1
        */
        outfile << std::endl;
        outfile << "Size of current CC: " << comp[intTurn].size() << std::endl;
        outfile << "[";
        for(std::list<int>::const_iterator it = comp[intTurn].begin(); it!=comp[intTurn].end(); ++it)
        {
            outfile << *it << " ";
        }
        outfile << "]" << std::endl;
        outfile << std::endl;
        heap.pop();
        outfile << "-------------------------------------------------------" << std::endl;
    }
    return count;
}