コード例 #1
0
void InterruptHandler(int interrupt, PCBPtr pcbRequest)
{
	switch (interrupt)
	{
	//if i/o request
	case 1:
		aCPU->runningPCB->state = 2;
		int number = rand() % 2;
		if((aCPU->IO1->owner == NULL) && (number == 1) ||
		   (aCPU->IO1->owner == NULL && aCPU->IO2->owner != NULL)) {
			printf("\nP%d moved to I/O1 device", aCPU->runningPCB->pid);
			aCPU->IO1->owner = aCPU->runningPCB;
		}
		else if((aCPU->IO2->owner == NULL) && (number == 0) ||
		   (aCPU->IO2->owner == NULL && aCPU->IO1->owner != NULL)) {
			printf("\nP%d moved to I/O2 device", aCPU->runningPCB->pid);
			aCPU->IO2->owner = aCPU->runningPCB;
		}
		else {
			printf("\nP%d moved to IO Queue", aCPU->runningPCB->pid);
			enqueue(aCPU->IoQueue, aCPU->runningPCB);
		}
		aCPU->runningPCB = dequeue(ReadyQPtr);
		aCPU->runningPCB->state = 0;
		printf("\nP%d selected from ready queue", aCPU->runningPCB->pid);
	break;
	//if keyboard request
	case 2:
		if(aCPU->Keyboard->keyboardFree == 1) {
			aCPU->runningPCB->state = 3;
			enqueue(aCPU->Keyboard->Blocked, aCPU->runningPCB);
			KBHASPCB = 1;
			printf("\nP%d was moved to the Keyboard's blocked queue", aCPU->runningPCB->pid);
		} else {
			aCPU->Keyboard->keyboardFree = 1;
			printf("\nP%d is now the Keyboard device's owner", aCPU->runningPCB->pid);
			aCPU->Keyboard->owner = aCPU->runningPCB;
			aCPU->runningPCB->state = 3;
		}
		aCPU->runningPCB = dequeue(ReadyQPtr);
		aCPU->runningPCB->state = 0;
		printf("\nP%d selected from ready queue", aCPU->runningPCB->pid);
	break;
	//if i/o 1 complete
	case 3:
		IO1INT = 0;
		printf("\nP%d's I/O interrupt complete", pcbRequest->pid);
		printf("\nP%d moved from I/O1 to ready queue", pcbRequest->pid);
		pcbRequest->state = 1;
		enqueue(ReadyQPtr, pcbRequest);

		if(aCPU->IoQueue->count != 0 && aCPU->IoQueue->first != aCPU->IoQueue->last ) {
			PCBPtr pcbPtr = dequeue(aCPU->IoQueue);
			printf("\nP%d moved from IO Queue, now owner of I/O1", pcbPtr->pid);
			aCPU->IO1->owner = pcbPtr;
			aCPU->IO1->IOAvailable = 1;
		} else {
			aCPU->IO1->IOAvailable = 0;
			aCPU->IO1->owner = NULL;
		}
	break;
	//if i/o 2 complete
	case 4:
		IO2INT = 0;
		printf("\nP%d's I/O interrupt complete", pcbRequest->pid);
		printf("\nP%d moved from I/O2 to ready queue", pcbRequest->pid);
		pcbRequest->state = 1;
		enqueue(ReadyQPtr, pcbRequest);

		if(aCPU->IoQueue->count != 0 && aCPU->IoQueue->first != aCPU->IoQueue->last) {
			PCBPtr pcbPtr = dequeue(aCPU->IoQueue);
			printf("\nP%d moved from IO Queue, now owner of I/O2", pcbPtr->pid);
			aCPU->IO2->owner = pcbPtr;
			aCPU->IO2->IOAvailable = 1;
		} else {
			aCPU->IO2->owner = NULL;
			aCPU->IO2->IOAvailable = 0;
		}
	break;
	//if keyboard complete
	case 5:
		KBINT = 0;
		enqueue(ReadyQPtr, pcbRequest);
		if(aCPU->Keyboard->Blocked->count != 0) {
			aCPU->Keyboard->owner = dequeue(aCPU->Keyboard->Blocked);
			aCPU->Keyboard->keyboardFree = 1;
			printf("\nKeyboard owner given to P%d", aCPU->Keyboard->owner->pid);
		} else {
			aCPU->Keyboard->owner = NULL;
			aCPU->Keyboard->keyboardFree = 0;
			KBHASPCB = 0;
		}
	break;
	//if  producer or consumer request for mutex
	case 6:
		//printf("\nMutex request made by P%d", aCPU->runningPCB->pid);

		//if (pthread_mutex_trylock(&(mutex[pcbRequest->sharedMemInd])) == 0) {
		//if (MutexMem[aCPU->runningPCB->sharedMemInd]->mutexLocked == 0) {
		//	printf("\nM%d is now locked by P%d", aCPU->runningPCB->sharedMemInd, aCPU->runningPCB->pid);
		//	setOwner(MutexMem[aCPU->runningPCB->sharedMemInd], aCPU->runningPCB);
		//	MutexMem[aCPU->runningPCB->sharedMemInd]->mutexLocked = 1;
			//aCPU->runningPCB = dequeue(aCPU->ReadyQueue);
			//aCPU->runningPCB->state = 0;
		//} else {
		//	printf("\nP%d was blocked", aCPU->runningPCB->pid);
		//	aCPU->runningPCB->state = 3;
		//	((MutexMem[aCPU->runningPCB->sharedMemInd])->waitingPCB) = aCPU->runningPCB;
		//	aCPU->runningPCB = dequeue(aCPU->ReadyQueue);
		//	aCPU->runningPCB->state = 0;
		//	printf("\nP%d is now running", aCPU->runningPCB->pid);
		//}
	break;
	//if its a timer request
	case 7:
		TIMERINT = 0;
		printf("\nTimer Interrupt Occurred");
		printf("\nP%d was moved to the Ready Queue", aCPU->runningPCB->pid);
		aCPU->runningPCB->state = 1;
		aCPU->runningPCB->curr_count = 0;
		enqueue(ReadyQPtr, aCPU->runningPCB);
		aCPU->runningPCB = dequeue(ReadyQPtr);
		aCPU->runningPCB->state = 0;
		printf("\nP%d selected from ready queue", aCPU->runningPCB->pid);
	break;
	default:
		printf("\nWrong Input");
	break;
	}
}
コード例 #2
0
ファイル: event_queue.hpp プロジェクト: respu/yield
 // yield::EventHandler
 void handle(YO_NEW_REF Event& event) {
   enqueue(event);
 }
コード例 #3
0
ファイル: t.c プロジェクト: dabbers/dabos
int kfork(char *filename)
{
  PROC *p;
  int  i, child;
  u16 word;
  u16  segment;

  /*** get a PROC for child process: ***/
  if ( (p = get_proc(&freeList)) == 0){
       printf("no more proc\n");
       return(-1);
  }

  /* initialize the new proc and its stack */
  p->status = READY;
  p->ppid = running->pid;
  p->parent = running;
  p->priority  = 1;                 // all of the same priority 1

  /******* write C code to to do THIS YOURSELF ********************
     Initialize p's kstack AS IF it had called tswitch() 
     from the entry address of body():

   HI   -1  -2    -3  -4   -5   -6   -7   -8    -9                LOW
      -------------------------------------------------------------
      |body| ax | bx | cx | dx | bp | si | di |flag|
      ------------------------------------------------------------
                                                ^
                                    PROC.ksp ---|

  ******************************************************************/

  // fill in resume address
  p->kstack[SSIZE-1] = (int)body;

  // save stack TOP address in PROC
  p->ksp = &(p->kstack[SSIZE - 9]);


  enqueue(&readyQueue, p);
 
  // make Umode image by loading /bin/u1 into segment
  segment = (p->pid + 1)*0x2000;
  load(filename, segment);

  /*************** WRITE C CODE TO DO THESE ******************
     Initialize new proc's ustak AS IF it had done INT 80
     from virtual address 0:

    HI  -1  -2  -3  -4  -5  -6  -7  -8  -9 -10 -11 -12
       flag uCS uPC uax ubx ucx udx ubp usi udi ues uds
     0x0200 seg  0   0   0   0   0   0   0   0  seg seg
                                                     ^
    PROC.uss = segment;           PROC.usp ----------|
 
  ***********************************************************/

	for (i = 1; i < 13; ++i)
	{
		switch(i) 
		{
			case 1:   word = 0x0200;  break;  // uFlag
			case 2:
			case 11:
			case 12:  word = segment; break;  // uCS, uES, uDS
			default:  word = 0;       break;  // pretty much everything else
		}

		put_word(word, segment, 0x2000-i*2);  // stack starts at highest end of segment
	}
	
    p->uss = segment;
    p->usp = 0x2000 - 24; // usp is byte address, x2

  printf("Proc%d forked a child %d segment=%x\n", running->pid,p->pid,segment);
  return(p->pid);
}
コード例 #4
0
ファイル: queue.c プロジェクト: ericfischer/misc
// test
int main() {
  struct node* queue = new_queue();
  queue = enqueue(queue, 1);
  queue = enqueue(queue, 2);
  print_list(queue);
}
コード例 #5
0
request *get_sock_request(int sock_fd)
{
	int fd;						/* socket */
#ifdef INET6
	struct sockaddr_in6 remote_addr;
#else
	struct sockaddr_in remote_addr;		/* address */
#endif
	int remote_addrlen = sizeof(remote_addr);
	request *conn;				/* connection */

	if (max_connections != -1 && status.connections >= max_connections)
		return NULL;

#ifdef INET6
	remote_addr.sin6_family = 0xdead;
#else
  remote_addr.sin_family = 0xdead;
#endif
	fd = accept(sock_fd, (struct sockaddr *) &remote_addr, &remote_addrlen);

	if (fd == -1) {
		if (errno == EAGAIN || errno == EWOULDBLOCK)	/* no requests */
			return;
		else {					/* accept error */
			log_error_time();
#if 0
			perror("accept");
#endif
			return NULL;
		}
	}
#ifdef DEBUGNONINET
	/*  This shows up due to race conditions in some Linux kernels 
	 *  when the client closes the socket sometime between 
	 *  the select() and accept() syscalls.
	 *  Code and description by Larry Doolittle <*****@*****.**>
	 */
#define HEX(x) (((x)>9)?(('a'-10)+(x)):('0'+(x)))
	if (remote_addr.sin_family != AF_INET) {
		struct sockaddr *bogus = (struct sockaddr *) &remote_addr;
		char *ap, ablock[44];
		int i;
		close(fd);
#ifdef BOA_TIME_LOG
		log_error_time();
#endif
		for (ap = ablock, i = 0; i < remote_addrlen && i < 14; i++) {
			*ap++ = ' ';
			*ap++ = HEX((bogus->sa_data[i] >> 4) & 0x0f);
			*ap++ = HEX(bogus->sa_data[i] & 0x0f);
		}
		*ap = '\0';
#ifdef BOA_TIME_LOG
		fprintf(stderr, "non-INET connection attempt: socket %d, "
				"sa_family = %hu, sa_data[%d] = %s\n",
				fd, bogus->sa_family, remote_addrlen, ablock);
#endif
		return NULL;
	}
#endif

	if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *) &sock_opt,
		sizeof(sock_opt))) == -1){
			die(NO_SETSOCKOPT);
			return NULL;
	}

	conn = new_request();
	conn->fd = fd;
	conn->status = READ_HEADER;
	conn->header_line = conn->client_stream;
	conn->time_last = time(NULL);
#ifdef USE_CHARSET_HEADER
	conn->send_charset = 1;
#endif

	/* nonblocking socket */
	if (fcntl(conn->fd, F_SETFL, NOBLOCK) == -1) {
#ifdef BOA_TIME_LOG
		log_error_time();
		perror("request.c, fcntl");
#endif
	}
	/* set close on exec to true */
	if (fcntl(conn->fd, F_SETFD, 1) == -1) {
#ifdef BOA_TIME_LOG
		log_error_time();
		perror("request.c, fcntl-close-on-exec");
#endif
	}

	/* large buffers */
	if (setsockopt(conn->fd, SOL_SOCKET, SO_SNDBUF, (void *) &sockbufsize,
				   sizeof(sockbufsize)) == -1)
		die(NO_SETSOCKOPT);

	/* for log file and possible use by CGI programs */
#ifdef INET6
	if (getnameinfo((struct sockaddr *)&remote_addr, 
									NRL_SA_LEN((struct sockaddr *)&remote_addr), 
									conn->remote_ip_addr, 20,
								 	NULL, 0, NI_NUMERICHOST)) {
#if 0
			fprintf(stderr, "[IPv6] getnameinfo failed\n");
#endif
			conn->remote_ip_addr[0]=0;
		}
#else
	strncpy(conn->remote_ip_addr, (char *) inet_ntoa(remote_addr.sin_addr), 20);
#endif

	/* for possible use by CGI programs */
#ifdef INET6
	conn->remote_port = ntohs(remote_addr.sin6_port);
#else
	conn->remote_port = ntohs(remote_addr.sin_port);
#endif

	if (virtualhost) {
#ifdef INET6
		char host[20];
		struct sockaddr_in6 salocal;
		int dummy;
				
		dummy = sizeof(salocal);
		if (getsockname(conn->fd, (struct sockaddr *) &salocal, &dummy) == -1)
									      die(SERVER_ERROR);
			if (getnameinfo((struct sockaddr *)&salocal,
		              NRL_SA_LEN((struct sockaddr *)&salocal),
			          host, 20,
				      NULL, 0, NI_NUMERICHOST)) {
#if 0
				fprintf(stderr, "[IPv6] getnameinfo failed\n");
#endif
			}else
				conn->local_ip_addr = strdup(host);
#else		
		struct sockaddr_in salocal;
		int dummy;

		dummy = sizeof(salocal);
		if (getsockname(conn->fd, (struct sockaddr *) &salocal, &dummy) == -1){
			die(SERVER_ERROR);
			return NULL;
		}
		conn->local_ip_addr = strdup(inet_ntoa(salocal.sin_addr));
#endif
	}	
	status.requests++;
	status.connections++;

	/* Thanks to Jef Poskanzer <*****@*****.**> for this tweak */
	{
		int one = 1;
		if (setsockopt(conn->fd, IPPROTO_TCP, TCP_NODELAY, (void *) &one,
			sizeof(one)) == -1){
			die(NO_SETSOCKOPT);
			return NULL;
		}
	}
	enqueue(&request_ready, conn);
	return conn;
}
コード例 #6
0
ファイル: task.cpp プロジェクト: SunnyGyb/rDSN
void task::exec_internal()
{
    task_state READY_STATE = TASK_STATE_READY;
    task_state RUNNING_STATE = TASK_STATE_RUNNING;

    if (_state.compare_exchange_strong(READY_STATE, TASK_STATE_RUNNING))
    {
        task* parent_task = nullptr;
        if (tls_task_info.magic == 0xdeadbeef)
        {
            parent_task = tls_task_info.current_task;
        }
        else
        {
            set_current_worker(nullptr);
        }
        
        tls_task_info.current_task = this;

        _spec->on_task_begin.execute(this);

        exec();
        
        if (_state.compare_exchange_strong(RUNNING_STATE, TASK_STATE_FINISHED))
        {
            _spec->on_task_end.execute(this);

            // signal_waiters(); [
            // inline for performance
            void* evt = _wait_event.load();
            if (evt != nullptr)
            {
                auto nevt = (utils::notify_event*)evt;
                nevt->notify();
            }
            // ]
        }

        // for timer
        else
        {
            if (!_wait_for_cancel)
            {
                _spec->on_task_end.execute(this);
                enqueue();
            }   
            else
            {
                _state.compare_exchange_strong(READY_STATE, TASK_STATE_CANCELLED);
                _spec->on_task_end.execute(this);

                // signal_waiters(); [
                // inline for performance
                void* evt = _wait_event.load();
                if (evt != nullptr)
                {
                    auto nevt = (utils::notify_event*)evt;
                    nevt->notify();
                }
                // ]
            }
        }
        
        tls_task_info.current_task = parent_task;
    }

    if (!_spec->allow_inline && !_is_null)
    {
        service::lock_checker::check_dangling_lock();
    }
}
コード例 #7
0
void* handle_client(void* args) 
{ 	
	int quit;
	client_t* newClient;
	int n;
	
	char *buffer1;
	char *buffer;
	char *newLineMessage;
	
	
	buffer=malloc(sizeof(char)*MAXMSG);/*store message coming from client*/
	
	
	
	quit=0;
	
	
	n=0;
	while(!quit){
	
	newClient=(client_t*)args;
	
	/*received data from client*/
	
	
	
	
	/*if message is bigger than the MAXMSG have to read more than ones because tcp it store and only sent when it read again.*/
	n=recvfrom(newClient->sd,buffer,MAXMSG,0,(struct sockaddr *)&(newClient->cliaddr),&(newClient->clilen));
	
	if (n == 0||n==-1) {
		/*n==0 connection is closed or n==-1 something wrong with client connection close the connection and put index -1 in client array I wont free that passion in array.I suppose it just wastage  of time.*/
		clients[newClient->index]->index=-1;
		close(newClient->sd);
		
		quit=1;
		
    		printf("Connection closed.\n");
    		
		
  	}
  	else{
		buffer[strlen(buffer)]='\0';
		newLineMessage=malloc(sizeof(char)*1000);/*message which is read line by line if it is big message and send line by line*/
		newLineMessage=strtok(buffer,"\n");
		sem_wait(&space);
		while (newLineMessage != NULL){
				/*read by line by  line and store in queue atthe same time put some headers about who send this message */
				buffer1=malloc(sizeof(char)*1000);/*message to be store in queue */
				strcpy(buffer1,newLineMessage);
				newLineMessage[0]='\0';
				strcat(buffer1,"\n");
				buffer1[strlen(buffer1)]='\0';
				
				
				/*put lock here to avoid race condition because If same time two thread(client) are accessed queue is going to be a big problem. */
				sem_wait(&enter);
				enqueue(buffer1);
				sem_post(&enter);
				newLineMessage= strtok(NULL,"\n");
				
  		}

		
		
		sem_post(&signalB);
	
	}
	}

	return NULL;	 
}
コード例 #8
0
void OutPacketBuffer::enqueueWord(u_int32_t word) {
  u_int32_t nWord = htonl(word);
  enqueue((unsigned char*)&nWord, 4);
}
コード例 #9
0
void OutPacketBuffer::useOverflowData() {
  enqueue(&fBuf[fPacketStart + fOverflowDataOffset], fOverflowDataSize);
  fCurOffset -= fOverflowDataSize; // undoes increment performed by "enqueue"
  resetOverflowData();
}
コード例 #10
0
void stackPush(struct node **top,int x){
	enqueue(top,x); //push value to queue
	count++; //get no of elements added to queue
		
}
コード例 #11
0
ファイル: servo4.c プロジェクト: omnister/velo
void housekeep() {
    usb_task(); 	// service periodic usb functions
    while (usb_cdc_kbhit() && (nqueue(&rxque0) < HIBUF)) {
	enqueue(&rxque0, usb_cdc_getc());
    }
}
コード例 #12
0
int AllocateInputBuffer(FrameBufferManager* fbm, VencAllocateBufferParam *buffer_param)
{
	int result = 0;
	int i= 0;

	if(!fbm)
	{
		return -1;
	}

	fbm->ABM_inputbuffer.buffer_num = buffer_param->nBufferNum;	
	fbm->ABM_inputbuffer.allocate_buffer = (VencInputBufferInfo*) \
												calloc(sizeof(VencInputBufferInfo),
												buffer_param->nBufferNum);

	if(!fbm->ABM_inputbuffer.allocate_buffer)
	{
		loge("allocate_buffer error");
		return -1;
	}

	fbm->size_y = buffer_param->nSizeY;
	fbm->size_c = buffer_param->nSizeC;

	memset(fbm->ABM_inputbuffer.allocate_buffer, 0, sizeof(VencInputBufferInfo)*buffer_param->nBufferNum);

	for(i=0; i<(int)buffer_param->nBufferNum; i++) {
		fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.nID  = i;
		fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirY = \
								(unsigned char *)EncAdapterMemPalloc(fbm->size_y);
		if(!fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirY)
		{
			loge("ABM_inputbuffer Y alloc error");
			break;
		}
		
		fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrPhyY = \
			(unsigned char *)EncAdapterMemGetPhysicAddressCpu(fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirY);

		EncAdapterMemFlushCache(fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirY, fbm->size_y);

		if(fbm->size_c > 0)
		{
			fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirC = \
						  (unsigned char *)EncAdapterMemPalloc((int)fbm->size_c);
			if(!fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirC)
			{
				loge("ABM_inputbuffer C alloc error");
				break;
			}
			
			fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrPhyC = \
				(unsigned char *)EncAdapterMemGetPhysicAddressCpu(fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirC);
			EncAdapterMemFlushCache(fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirC, fbm->size_c);
		}
	}

	if(i < (int)buffer_param->nBufferNum) 
	{
		for(i=0; i<(int)buffer_param->nBufferNum; i++) 
		{
			if(fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirY)
			{
			    EncAdapterMemPfree(fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirY);
			}

			if(fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirC)
			{
			    EncAdapterMemPfree(fbm->ABM_inputbuffer.allocate_buffer[i].inputbuffer.pAddrVirC);
			}
		}

		free(fbm->ABM_inputbuffer.allocate_buffer);
		fbm->ABM_inputbuffer.allocate_buffer = NULL;
		return -1;
	}

	// all allocate buffer enquene
	for(i=0; i<(int)buffer_param->nBufferNum; i++) 
	{
		enqueue(&fbm->ABM_inputbuffer.allocate_queue,&fbm->ABM_inputbuffer.allocate_buffer[i]);
	}

	pthread_mutex_init(&fbm->ABM_inputbuffer.mutex, NULL);

	return 0;
}
コード例 #13
0
ファイル: 04D.c プロジェクト: neotaso/pp
int main(void) {
  char buf[BUFSIZE];
  char canvas[N][N];
  int i,j;
  elemtype point,pos;
  struct queue que;
  initqueue(&que);
  
  for (i = 0; i < N; i++) {
    fgets(buf, BUFSIZE, stdin);
    for (j = 0; j < N && (buf[j] != '\n' && buf[j] != '\0'); j++)
      canvas[i][j] = buf[j];
    while (j < N) canvas[i][j++] = ' ';
  }

  point.x=point.y=N/2;
  canvas[point.y][point.x]=C;
  enqueue(&que,point);

  while(!queueempty(&que)){
    point=dequeue(&que);
    if(point.y!=0){
      if(canvas[point.y-1][point.x]==' '){
	pos.x=point.x;
	pos.y=point.y-1;
	enqueue(&que,pos);
	canvas[pos.y][pos.x]=C;
      }
    }
    if(point.x!=0){
      if(canvas[point.y][point.x-1]==' '){
	pos.x=point.x-1;
	pos.y=point.y;
	enqueue(&que,pos);
	canvas[pos.y][pos.x]=C;
      }
    }
    if(point.y!=N-1){
      if(canvas[point.y+1][point.x]==' '){
	pos.x=point.x;
	pos.y=point.y+1;
	enqueue(&que,pos);
	canvas[pos.y][pos.x]=C;
      }
    }
    if(point.x!=N-1){
      if(canvas[point.y][point.x+1]==' '){
	pos.x=point.x+1;
	pos.y=point.y;
	enqueue(&que,pos);
	canvas[pos.y][pos.x]=C;
      }
    }
  }

  for(i=0;i<N;i++){
    for(j=0;j<N;j++)printf("%c",canvas[i][j]);
    printf("\n");
  }
  return 0;
}
コード例 #14
0
//CPU Thread Function
void *CPURun(void *args)
{
	//put the first PCB as running
	if (aCPU->runningPCB == NULL)
	{
		aCPU->runningPCB = dequeue(ReadyQPtr);
		aCPU->runningPCB->state = 0;
	}

	//1 for interrupt has occurred, 0 for interrupt did not occur
	int interruptOccurred = (IO1INT || IO2INT || KBINT || TIMERINT);

	while(aCPU->count > 0)
	{	
		
		//PRINT OUT OF CURRENT SETTINGS
		sleep(1);
		printf("\n\n\n\n\n\n\n\n");
		printf("P%d - running", aCPU->runningPCB->pid);
		if (aCPU->IO1->owner != NULL) printf("\nI/O1 - P%d", aCPU->IO1->owner->pid);
		if (aCPU->IO2->owner != NULL) printf("\nI/O2 - P%d", aCPU->IO2->owner->pid);
		if (aCPU->IoQueue->count > 0)
		{
			printf("\nI/O Waiting - ");
			printQueue(aCPU->IoQueue);
		}
		int m;
		for(m = 0; m < pcproc_count; m++)
		{
			if (mutex[m]->owner != NULL) printf("\nM%d - P%d owns", m, mutex[m]->owner->pid);
		}
		for(m = 0; m < pcproc_count * 2; m++)
		{
			if (condVar[m] != NULL ) 
			{
				if (condVar[m]->pcbQueue->count > 0)
				{
					printf("\nCV%d - ", m);
					printQueue(condVar[m]->pcbQueue);
				}
			}
		}
		//Keyboard
		//printf();
		printf("\n-------------------------");
		
		if(interruptOccurred == 0)
		{
			if(aCPU->runningPCB->curr_count > WAIT_TIME)
			{
				runForCount = WAIT_TIME;
			}
		} 
		else
		{
			runForCount = aCPU->runningPCB->curr_count;
		}
		runForCount = rand() % 7;
		
		while(runForCount > 0)
		{
			runForCount--;
			aCPU->runningPCB->curr_count++;
			if (aCPU->runningPCB->curr_count == WAIT_TIME) TIMERINT = 1;
			interruptOccurred = (IO1INT || IO2INT || KBINT || TIMERINT);

			if (interruptOccurred)
			{
				if(TIMERINT)
				{
					InterruptHandler( 7, aCPU->runningPCB);
					runForCount = 0;
				}
				if(IO1INT) InterruptHandler( 3, aCPU->IO1->owner);
				if(IO2INT) InterruptHandler( 4, aCPU->IO2->owner);
				if(KBINT) InterruptHandler( 5, aCPU->Keyboard->owner);
			}
			int processType = aCPU->runningPCB->process->proc_type;
			if ((processType == 0) && (runForCount != 0))
			{
				if (runForCount == 1)
				{
					TIMERINT = 1;
				}
			}
			else if ((processType == 1) && (runForCount != 0))
			{
				int i;
				for(i = 0; i < aCPU->runningPCB->process->no_requests; i++)
				{
					if ( (rand() % 10) == (rand() % 10) )
					{
						aCPU->runningPCB->state = 2;
						aCPU->runningPCB->curr_count = runForCount;
						runForCount = 0;
						InterruptHandler( 1, aCPU->runningPCB);
					}
					else if ( runForCount == 1 )
					{
						TIMERINT = 1;
					}
				}
			}
			else if ((processType == 2) && (runForCount != 0))
			{
				InterruptHandler( 2, aCPU->runningPCB);
				runForCount = 0;
			}
			else if ((processType == 3) || (processType == 4) && (runForCount != 0))
			{
				if(processType == 3)
				{
					pthread_create(&aCPU->producer_thread[aCPU->runningPCB->sharedMemInd], NULL, incCount, (void *) aCPU->runningPCB);
				}
				else if (processType == 4)
				{
					pthread_create(&aCPU->consumer_thread[aCPU->runningPCB->sharedMemInd], NULL, resetCount, (void *) aCPU->runningPCB);
				}
				aCPU->runningPCB->state = 1;
				printf("\nP%d returned to ready queue", aCPU->runningPCB->pid);
				enqueue(ReadyQPtr, aCPU->runningPCB);
				aCPU->runningPCB = dequeue(ReadyQPtr);
				printf("\nP%d selected from ready queue", aCPU->runningPCB->pid);
				runForCount = 0;
			}
			aCPU->count--;
			if (aCPU->count == 0)
			{
			cpuRunning = 0;
			KBDevDestructor(aCPU->Keyboard);
			pthread_exit(NULL);
			}
		}
	}
}
コード例 #15
0
int main()
{
    int i,j,V,E;

    FILE* fp=fopen("graph.txt","r"); //for sample graph at http://www.geeksforgeeks.org/greedy-algorithms-set-6-dijkstras-shortest-path-algorithm/

    printf("Enter no. of vertices and edges : ");
    fscanf(fp,"%d%d",&V,&E);
    //scanf("%d%d",&V,&E);
    printf("V=%d, E=%d\n",V,E);

    //int from[20];
    //int to[20];

    int a,b,c;

    int adj[MAX][MAX];



     for(i=0;i<=V;i++)
     {
        for(j=0;j<=V;j++)
        {
            adj[i][j]=-1;
        }
     }

    for(i=1;i<=E;i++)
    {
        fscanf(fp,"%d%d%d",&a,&b,&c);//alphabetical, undirected edges (source, destination, weight)
        //scanf("%d%d%d",&a,&b,&c);
        adj[a][b]=c;
        adj[b][a]=c;
        //printf("%d %d %d\n",a,b,c);
    }

    //starting node=0



   /* for(i=0;i<=V;i++)
    {
        for(j=0;j<=V;j++)
        {
            printf("%d ",adj[i][j]);
        }
        printf("\n");
    } */

    int distance[MAX];
    int visited[MAX]={0};
    for(i=1;i<=V;i++)
    {
        distance[i]=999999;//infinity
    }
    distance[0]=0;
    int count=0;

    Q.front=-1;
    Q.rear=-1;

    int k=0;
    enqueue(k);


    while(count<=V)
    {
        k=dequeue();
        for(i=0;i<V;i++)
        {
            if(adj[k][i]>=0 && visited[i]==0)
            {
                //printf("dk=%d,di+adj[k][i]=%d\n",distance[k],distance[i]+adj[k][i]);
                distance[i]=min(distance[i],distance[k]+adj[k][i]);
                enqueue(i);
            }
        }
        visited[k]=1;
        count++;

    }

    for(i=0;i<V;i++)
        printf("%d %d\n",i,distance[i]);

    return 0;
}
コード例 #16
0
ファイル: kwset.c プロジェクト: 00027jang27/git
/* Compute the shift for each trie node, as well as the delta
   table and next cache for the given keyword set. */
const char *
kwsprep (kwset_t kws)
{
  register struct kwset *kwset;
  register int i;
  register struct trie *curr;
  register char const *trans;
  unsigned char delta[NCHAR];

  kwset = (struct kwset *) kws;

  /* Initial values for the delta table; will be changed later.  The
     delta entry for a given character is the smallest depth of any
     node at which an outgoing edge is labeled by that character. */
  memset(delta, kwset->mind < UCHAR_MAX ? kwset->mind : UCHAR_MAX, NCHAR);

  /* Check if we can use the simple boyer-moore algorithm, instead
     of the hairy commentz-walter algorithm. */
  if (kwset->words == 1 && kwset->trans == NULL)
    {
      char c;

      /* Looking for just one string.  Extract it from the trie. */
      kwset->target = obstack_alloc(&kwset->obstack, kwset->mind);
      if (!kwset->target)
	return "memory exhausted";
      for (i = kwset->mind - 1, curr = kwset->trie; i >= 0; --i)
	{
	  kwset->target[i] = curr->links->label;
	  curr = curr->links->trie;
	}
      /* Build the Boyer Moore delta.  Boy that's easy compared to CW. */
      for (i = 0; i < kwset->mind; ++i)
	delta[U(kwset->target[i])] = kwset->mind - (i + 1);
      /* Find the minimal delta2 shift that we might make after
	 a backwards match has failed. */
      c = kwset->target[kwset->mind - 1];
      for (i = kwset->mind - 2; i >= 0; --i)
	if (kwset->target[i] == c)
	  break;
      kwset->mind2 = kwset->mind - (i + 1);
    }
  else
    {
      register struct trie *fail;
      struct trie *last, *next[NCHAR];

      /* Traverse the nodes of the trie in level order, simultaneously
	 computing the delta table, failure function, and shift function. */
      for (curr = last = kwset->trie; curr; curr = curr->next)
	{
	  /* Enqueue the immediate descendents in the level order queue. */
	  enqueue(curr->links, &last);

	  curr->shift = kwset->mind;
	  curr->maxshift = kwset->mind;

	  /* Update the delta table for the descendents of this node. */
	  treedelta(curr->links, curr->depth, delta);

	  /* Compute the failure function for the descendants of this node. */
	  treefails(curr->links, curr->fail, kwset->trie);

	  /* Update the shifts at each node in the current node's chain
	     of fails back to the root. */
	  for (fail = curr->fail; fail; fail = fail->fail)
	    {
	      /* If the current node has some outgoing edge that the fail
		 doesn't, then the shift at the fail should be no larger
		 than the difference of their depths. */
	      if (!hasevery(fail->links, curr->links))
		if (curr->depth - fail->depth < fail->shift)
		  fail->shift = curr->depth - fail->depth;

	      /* If the current node is accepting then the shift at the
		 fail and its descendents should be no larger than the
		 difference of their depths. */
	      if (curr->accepting && fail->maxshift > curr->depth - fail->depth)
		fail->maxshift = curr->depth - fail->depth;
	    }
	}

      /* Traverse the trie in level order again, fixing up all nodes whose
	 shift exceeds their inherited maxshift. */
      for (curr = kwset->trie->next; curr; curr = curr->next)
	{
	  if (curr->maxshift > curr->parent->maxshift)
	    curr->maxshift = curr->parent->maxshift;
	  if (curr->shift > curr->maxshift)
	    curr->shift = curr->maxshift;
	}

      /* Create a vector, indexed by character code, of the outgoing links
	 from the root node. */
      for (i = 0; i < NCHAR; ++i)
	next[i] = NULL;
      treenext(kwset->trie->links, next);

      if ((trans = kwset->trans) != NULL)
	for (i = 0; i < NCHAR; ++i)
	  kwset->next[i] = next[U(trans[i])];
      else
	memcpy(kwset->next, next, NCHAR * sizeof(struct trie *));
    }

  /* Fix things up for any translation table. */
  if ((trans = kwset->trans) != NULL)
    for (i = 0; i < NCHAR; ++i)
      kwset->delta[i] = delta[U(trans[i])];
  else
    memcpy(kwset->delta, delta, NCHAR);

  return NULL;
}
コード例 #17
0
ファイル: LP.c プロジェクト: MarcusxDM/PaiDePiper
void compress()
{
	Hashtable *ht = createHashtable();
	linkedList *charBits = newLinkedList();
    FILE *file = fopen("file.txt", "r");
    FILE *backp = fopen("backp.txt","w");
    FILE *backp2 = fopen("backp2.txt","w");
    PriorityQueue * queue = createPriorityQueue();
    int characters[256],i,count=0,j,count2=0;
    unsigned char currentChar;
    memset(characters,0,sizeof(characters));

    if (file == NULL)
    {
        printf ("ERROR 404: FILE NOT FOUND\n");
        exit(0);
    }
    else
    {
        do
        {
            currentChar = fgetc(file);
            if(currentChar == UNSIGNED_EOF)
            {
                break;
            }
            characters[currentChar]++;
            count2++;
        }
        while(currentChar != UNSIGNED_EOF);
    }
    for(i=0; i < UNSIGNED_EOF; i++)
    {
        if(characters[i]!=0)
        {
            count++;
            enqueue(queue,i,characters[i],NULL);
        }
    }
    for(j = count ; j>1 ; j--)
    {
        dequeue(queue);
    }
	generateBits(ht, charBits, returnBT(queue));
	freeBT(returnBT(queue));
	rewind(file);
	do
    {
        currentChar = fgetc(file);
        if(currentChar == UNSIGNED_EOF)
        {
            break;
        }
        fprintf(backp,"%s",get(ht,currentChar));
    }
    while(currentChar != UNSIGNED_EOF);

    fprintf(backp2,"%d\n",count); // SALVA QUANTAS LINHAS DE HASH TERÁ NO ARQUIVO

    for(i=0; i < UNSIGNED_EOF; i++)
    {
        if(characters[i]!=0)
        {
            fprintf(backp2,"%c %s\n",i,get(ht,i)); //SALVA QUAL CARACTERE E O SEU CODIGO ASCII REDUZIDO NA HASH
        }
    }
    fprintf(backp2,"%d\n",count2); // SALVA A QUANTIDADE DE CHARS QUE EXISTIRÃO
    fclose(backp);
    writeCompressedData(backp2);
	fclose(backp2);
    fclose(file);
    rename("backp2.txt","compressed.txt");
    remove("backp.txt");
}
コード例 #18
0
void LLObjectMediaDataClient::fetchMedia(LLMediaDataClientObject *object)
{
	// Create a get request and put it in the queue.
	enqueue(new RequestGet(object, this));
}
コード例 #19
0
ファイル: util.c プロジェクト: OpenKod/src
/*
 * Opens a file and processes it.  Each file is processed line-by-line
 * passing the lines to procline().
 */
int
procfile(const char *fn)
{
	struct file *f;
	struct stat sb;
	struct str ln;
	mode_t s;
	int c, t;

	mcount = mlimit;

	if (strcmp(fn, "-") == 0) {
		fn = label != NULL ? label : getstr(1);
		f = grep_open(NULL);
	} else {
		if (!stat(fn, &sb)) {
			/* Check if we need to process the file */
			s = sb.st_mode & S_IFMT;
			if (s == S_IFDIR && dirbehave == DIR_SKIP)
				return (0);
			if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
				|| s == S_IFSOCK) && devbehave == DEV_SKIP)
					return (0);
		}
		f = grep_open(fn);
	}
	if (f == NULL) {
		file_err = true;
		if (!sflag)
			warn("%s", fn);
		return (0);
	}

	ln.file = grep_malloc(strlen(fn) + 1);
	strcpy(ln.file, fn);
	ln.line_no = 0;
	ln.len = 0;
	linesqueued = 0;
	tail = 0;
	ln.off = -1;

	for (c = 0;  c == 0 || !(lflag || qflag); ) {
		ln.off += ln.len + 1;
		if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL || ln.len == 0) {
			if (ln.line_no == 0 && matchall)
				exit(0);
			else
				break;
		}
		if (ln.len > 0 && ln.dat[ln.len - 1] == '\n')
			--ln.len;
		ln.line_no++;

		/* Return if we need to skip a binary file */
		if (f->binary && binbehave == BINFILE_SKIP) {
			grep_close(f);
			free(ln.file);
			free(f);
			return (0);
		}
		/* Process the file line-by-line */
		if ((t = procline(&ln, f->binary)) == 0 && Bflag > 0) {
			enqueue(&ln);
			linesqueued++;
		}
		c += t;
		if (mflag && mcount <= 0)
			break;
	}
	if (Bflag > 0)
		clearqueue();
	grep_close(f);

	if (cflag) {
		if (!hflag)
			printf("%s:", ln.file);
		printf("%u\n", c);
	}
	if (lflag && !qflag && c != 0)
		printf("%s%c", fn, nullflag ? 0 : '\n');
	if (Lflag && !qflag && c == 0)
		printf("%s%c", fn, nullflag ? 0 : '\n');
	if (c && !cflag && !lflag && !Lflag &&
	    binbehave == BINFILE_BIN && f->binary && !qflag)
		printf(getstr(8), fn);

	free(ln.file);
	free(f);
	return (c);
}
コード例 #20
0
void LLObjectMediaDataClient::updateMedia(LLMediaDataClientObject *object)
{
	// Create an update request and put it in the queue.
	enqueue(new RequestUpdate(object, this));
}
コード例 #21
0
ファイル: queue.c プロジェクト: n-t-roff/DWB3.3
// Fill the staging area with a minimal chunk of input ranges.
int mergestream::prime()
{
	if (dbg & 4)
		printf("#entering mergestream::prime()\n");
	if (!empty())
		return 1;
	int brkok = 1;			// is it OK to break after the last
					// VBOX that was added to the stage?
	int needheight = -1;		// minimum acceptable height of the
					// chunk being constructed on stage
	// If the range at the head of any queue is breaking,
	// deal with it first.
	if (squeue.more() && squeue.current()->breaking())
		enqueue(squeue.dequeue());
	else if (bfqueue.more() && (bfqueue.current()->breaking() ||
		(bfqueue.serialno() < squeue.serialno())))
		enqueue(bfqueue.dequeue());
	else if (ufqueue.more() && (ufqueue.current()->breaking() ||
		(ufqueue.serialno() < squeue.serialno())))
		enqueue(ufqueue.dequeue());
	else while (squeue.more()) {
		// Fill the stage with enough ranges to be a valid chunk.
		range *r = squeue.dequeue();
		if (r->isvbox()) {	// VBOX
			if (dbg & 16)
				printf("#VBOX: !empty: %d; brkok: %d; vsince: %d\n",
					!empty(), brkok, currpage->vsince);
			if (!empty()	// there's something there
				&& brkok
					// it's OK to break here
				&& currpage->vsince >= 2
					// enough stream has gone onto this page
				&& rawht() >= needheight
					// current need has been satisfied
				) {
					// the stage already contains enough
					// ranges, so this one can wait
				r->enqueue();
				break;
			} else {
				if (r->rawht() > 0) {
					++currpage->vsince;
					brkok = r->brkafter();
				}
				enqueue(r);
			}
		} else if (r->isnested() || r->issp()) {	// US, SP
			if (!empty() && rawht() >= needheight) {
					// enough already, wait
				r->enqueue();
				break;
			}
			currpage->vsince = 0;
			enqueue(r);
			if (height() >= needheight)
				break;
		} else if (r->isneed()) {	// NE
			if (!empty() && rawht() >= needheight) {
					// not currently working on an unsatisfied NEed 
				r->enqueue();
				break;
			}
					// deal with overlapping NEeds
			needheight = rawht() + max(needheight - rawht(), r->needht());
			enqueue(r);
		} else if (r->forceflush() == NO) {
			enqueue(r);
		} else if (r->forceflush() == YES) {
			currpage->vsince = 0;
			if (!empty()) {
					// ready or not, r must wait
				r->enqueue();
				break;
			}
			enqueue(r);
			break;
		} else
			ERROR "unexpected  %s[%s] in prime(), line %d\n",
				r->type_name(), r->headstr(), r->lineno() FATAL;
	}
	return more();			// 0 if nothing was staged
}
コード例 #22
0
// called if the media filter passes the request
void LLObjectMediaNavigateClient::doNavigate(LLMediaDataClientObject *object, U8 texture_index, const std::string &url)
{
	// Create a get request and put it in the queue.
	enqueue(new RequestNavigate(object, this, texture_index, url));
}
コード例 #23
0
void free_request(request ** list_head_addr, request * req)
{
	if (req->buffer_end)
		return;

	dequeue(list_head_addr, req);	/* dequeue from ready or block list */

	if (req->buffer_end)
		FD_CLR(req->fd, &block_write_fdset);
	else {
		switch (req->status) {
		case PIPE_WRITE:
		case WRITE:
			FD_CLR(req->fd, &block_write_fdset);
			break;
		case PIPE_READ:
			FD_CLR(req->data_fd, &block_read_fdset);
			break;
		case BODY_WRITE:
			FD_CLR(req->post_data_fd, &block_write_fdset);
			break;
		default:
			FD_CLR(req->fd, &block_read_fdset);
		}
	}

	if (req->logline)			/* access log */
		log_access(req);

	if (req->data_mem)
		munmap(req->data_mem, req->filesize);
	
	if (req->data_fd)
		close(req->data_fd);
	
	if (req->response_status >= 400)
		status.errors++;

	if ((req->keepalive == KA_ACTIVE) &&
		(req->response_status < 400) &&
		(++req->kacount < ka_max)) {

		request *conn;

		conn = new_request();
		conn->fd = req->fd;
		conn->status = READ_HEADER;
		conn->header_line = conn->client_stream;
		conn->time_last = time(NULL);
		conn->kacount = req->kacount;
#ifdef SERVER_SSL
		conn->ssl = req->ssl; /*MN*/
#endif /*SERVER_SSL*/
		
		/* we don't need to reset the fd parms for conn->fd because
		   we already did that for req */
		/* for log file and possible use by CGI programs */
		
		strcpy(conn->remote_ip_addr, req->remote_ip_addr);

		/* for possible use by CGI programs */
		conn->remote_port = req->remote_port;
		
		if (req->local_ip_addr)
			conn->local_ip_addr = strdup(req->local_ip_addr);

		status.requests++;
		
		if (conn->kacount + 1 == ka_max)
			SQUASH_KA(conn);
				
		conn->pipeline_start = req->client_stream_pos - 
								req->pipeline_start;
		
		if (conn->pipeline_start) {
			memcpy(conn->client_stream,
				req->client_stream + req->pipeline_start,
				conn->pipeline_start);			
			enqueue(&request_ready, conn);				
		} else
			block_request(conn);
	} else{
		if (req->fd != -1) {
			status.connections--;
			safe_close(req->fd);
		}
		req->fd = -1;
#ifdef SERVER_SSL
		SSL_free(req->ssl);
#endif /*SERVER_SSL*/
	}

	if (req->cgi_env) {
		int i = COMMON_CGI_VARS;
		req->cgi_env[req->cgi_env_index]=0;
		while (req->cgi_env[i])
		{
			free(req->cgi_env[i++]);
		}
		free(req->cgi_env);
	}
	if (req->pathname)
		free(req->pathname);
	if (req->path_info)
		free(req->path_info);
	if (req->path_translated)
		free(req->path_translated);
	if (req->script_name)
		free(req->script_name);
	if (req->query_string)
		free(req->query_string);
	if (req->local_ip_addr)
		free(req->local_ip_addr);
/*
 *	need to clean up if anything went wrong
 */
	if (req->post_file_name) {
		unlink(req->post_file_name);
		free(req->post_file_name);
		close(req->post_data_fd);
		req->post_data_fd = -1;
		req->post_file_name = NULL;
	}

	enqueue(&request_free, req);	/* put request on the free list */

	return;
}
コード例 #24
0
ファイル: t.c プロジェクト: bhanderson/cpts460
int scheduler(){
	if (running->status == READY)
		enqueue(&readyQueue, running);
	//enqueue(running, &readyQueue);
	running = dequeue(&readyQueue);
}
コード例 #25
0
ファイル: 15C_Hw_2.c プロジェクト: tokkiboi/programming
int main( void )
{
	QUEUE *queue;
	QUEUE_NODE *queueNode;
	void* dataInPtr;
	void* dataOutPtr;
	int queue_status;
	int queue_element_count;
	
	queue = createQueue ();

	//a.print queue status, Empty
	printf("Test Case(a) : Print queue status, Empty\n\n");
	queue_status = emptyQueue(queue);
	if(queue_status == 1)
	{
		printf("queue status : Empty\n");
	}
	else
	{
		printf("queue status : not empty\n");
	}
	printf("\n\n");
	
	//b.Dequeue and print data. Should return error
	printf("Test Case(b) : Dequeue and print data\n\n");
	dequeue( queue, &dataOutPtr );
	printf("\n\n");
		
	//c. Enqueue data into queue
	printf("Test Case(c) : Enqueue data into queue : Ann\n\n");
	dataInPtr = (char*)calloc((strlen("Ann")+1), sizeof(char) );
	strcpy(dataInPtr, "Ann");
	enqueue( queue, dataInPtr);
	
	//d. Enqueue data into queue
	printf("Test Case(d) : Enqueue data into queue : Bob\n\n");
	dataInPtr = (char*)calloc(strlen("Bob")+1, sizeof(char) );
	strcpy(dataInPtr, "Bob");
	enqueue( queue, dataInPtr);

	//e.Print queue status, Empty
	printf("Test Case(e) : Print queue status, Empty\n\n");
	queue_status = emptyQueue(queue);
	if(queue_status == 1)
	{
		printf("queue status : Empty\n");
	}
	else
	{
		printf("queue status : not empty\n");
	}
	printf("\n\n");
	
	//f.Print queue status, Full
	printf("Test Case(f) : Print queue status, Full\n\n");
	queue_status = fullQueue( queue );
	if(queue_status == 1)
	{
		printf("queue status : Full\n");
	}
	else
	{
		printf("queue status : not full\n");
	}
	printf("\n\n");
	
	//g. Print data at the front
	printf("Test Case(g) : Print data at the front\n\n");
	queueFront  ( queue, &dataOutPtr );
	printf("Data at the queue front is : %s\n", queue->front->dataPtr);
	printf("\n\n");
	
	//h. Print data at the rear
	printf("Test Case(h) : Print data at the rear\n\n");
	queueRear   ( queue, &dataOutPtr );
	printf("Data at the queue rear is : %s\n", queue->rear->dataPtr);
	printf("\n\n");

	//i. Print entire queue
	printf("Test Case(i) : Print entire queue\n\n");
	printf("The entire queue is : ");
	queueNode = queue->front;
	while(queueNode != NULL)
	{
		printf("%s ", queueNode->dataPtr);
		queueNode = queueNode->link;
	}
	printf("\n\n");

	//j.Print number of element in queue
	printf("Test Case(j) : Print number of element in queue\n\n");
	queue_element_count = queueCount( queue );
	printf("total no of element in queue is %d\n", queue_element_count);
	printf("\n\n");
	
	//k.Dequeue and print data
	printf("Test Case(k) : Dequeue and print data\n\n");
	dequeue( queue, &dataOutPtr );
	printf("after dequeueing we got : %s\n", dataOutPtr);
	free(dataOutPtr);
	printf("\n\n");

	//l.Dequeue and print data
	printf("Test Case(l) : Dequeue and print data\n\n");
	dequeue( queue, &dataOutPtr );
	printf("after dequeueing we got : %s\n", dataOutPtr);
	free(dataOutPtr);
	printf("\n\n");
	
	//m.Dequeue and print data
	printf("Test Case(m) : Dequeue and print data\n\n");
	dequeue( queue, &dataOutPtr );
	printf("\n\n");
	
	//n. Enqueue data into queue
	printf("Test Case(n) : Enqueue and print data : Dan\n\n");
	dataInPtr = (char*)calloc(strlen("Dan")+1, sizeof(char) );
	strcpy(dataInPtr, "Dan");
	enqueue( queue, dataInPtr );
	
	//o. Print data at the front
	printf("Test Case(o) : Print data at the front\n\n");
	queueFront  ( queue, &dataOutPtr );
	printf("Data at the queue front is : %s\n", queue->front->dataPtr);
	printf("\n\n");
	
	//p. Print data at the rear
	printf("Test Case(p) : Print data at the rear\n\n");
	queueRear   ( queue, &dataOutPtr );
	printf("Data at the queue rear is : %s\n", queue->rear->dataPtr);
	printf("\n\n");
	

	//q. Enqueue data into queue
	printf("Test Case(q) : Enqueue data into queue : Tom\n\n");
	dataInPtr = (char*)calloc(strlen("Tom")+1, sizeof(char) );
	strcpy(dataInPtr, "Tom");
	enqueue( queue, dataInPtr );
	
	//r. print data at the front
	printf("Test Case(r) : Print data at the front\n\n");
	queueFront( queue, &dataOutPtr );
	printf("Data at the queue front is : %s\n", queue->front->dataPtr);
	printf("\n\n");
	
	//s. Print data at the rear
	printf("Test Case(s) : Print data at the rear\n\n");
	queueRear   ( queue, &dataOutPtr );
	printf("Data at the queue rear is : %s\n", queue->rear->dataPtr);
	printf("\n\n");

	//t. Destroy queue and quit
	printf("Test Case(t) : Destroy queue and quit\n\n");
	destroyQueue( queue );
	#ifdef _MSC_VER
    printf( _CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Memory Leak\n");
    #endif    
	system("pause");
    return 0;
}
コード例 #26
0
ファイル: intr.c プロジェクト: SJTU-IPADS/COREMU
/* Insert an intrrupt into queue.
 * Signal-unsafe. block the signal in the lock free function */
static inline void coremu_put_intr(CMCore *core, void *e)
{
    enqueue(core->intr_queue, (long)e);
}
コード例 #27
0
/* 
Enqueue a message (buff) onto the queue env. 
*/
int enqueue_wrppr(void *env, char *buff, int size){    return enqueue((queue *)env, buff, size);}
コード例 #28
0
ファイル: queue.c プロジェクト: stonesandpebbles/cs50
/**
 * Implements some simple test code for our queue
 */
int main(void)
{
    // initialize the queue
    q.head = 0;
    q.strings = malloc(INITIAL_CAPACITY * sizeof(char*));
    q.size = 0;
    q.capacity = INITIAL_CAPACITY;

    printf("Enqueueing %d strings...", TEST_CAPACITY);
    for (int i = 0; i < TEST_CAPACITY; i++)
    {
        char str[12];
        sprintf(str, "%d", i);
        enqueue(strdup(str));
    }
    printf("done!\n");

    printf("Making sure that the queue size is indeed %d...", TEST_CAPACITY);
    assert(q.size == TEST_CAPACITY);
    printf("good!\n");

    printf("Dequeueing everything...");
    char* str_array[TEST_CAPACITY];
    for (int i = 0; i < TEST_CAPACITY; i++)
    {
        str_array[i] = dequeue();
    }
    printf("done!\n");

    printf("Making sure that dequeue() returned values in FIFO order...");
    for (int i = 0; i < TEST_CAPACITY; i++)
    {
        char str[12];
        sprintf(str, "%d", i);
        assert(strcmp(str_array[i], str) == 0);
        free(str_array[i]);
    }
    printf("good!\n");

    printf("Making sure that the queue is now empty...");
    assert(q.size == 0);
    printf("good!\n");

    printf("Making sure that dequeue() now returns NULL...");
    assert(dequeue() == NULL);
    printf("good!\n");

    printf("Making sure that the head wraps around appropriately...");
    for (int i = 0; i < TEST_CAPACITY; i++)
    {
        enqueue("cs50!");
    }

    // to make sure that they adjust the head pointer appropriately, we'll
    // enqueue and dequeue a bunch of times to make sure they don't just
    // walk off the end of the char* strings[] array
    for (int i = 0; i < TEST_CAPACITY * 10; i++)
    {
        for (int j = 0; j < TEST_CAPACITY / 2; j++)
        {
            assert(dequeue());
        }

        for (int j = 0; j < TEST_CAPACITY / 2; j++)
        {
            enqueue("cs50!");
        }
    }
    printf("good!\n");

    // reinitialize the queue
    free(q.strings);
    q.head = 0;
    q.strings = malloc(INITIAL_CAPACITY * sizeof(char*));
    q.size = 0;
    q.capacity = INITIAL_CAPACITY;

    for (int i = 0; i < TEST_CAPACITY; i++)
    {
        enqueue("cs50!");
    }

    for (int i = 0; i < TEST_CAPACITY / 2; i++)
    {
        assert(dequeue());
    }

    for (int i = 0; i < TEST_CAPACITY * 2; i++)
    {
        enqueue("cs50!");
    }

    printf("\n********\nSuccess!\n********\n");

    // clean up
    free(q.strings);

    return 0;
}
コード例 #29
0
ファイル: t.c プロジェクト: dabbers/dabos
int ufork()
{
	PROC *p;
	int  i, child;
	u16  segment;
    u16 wurd;

	int from_segment = (running->pid + 1) * 0x2000;

	p = get_proc(&freeList);

	if ( p == 0 )
	{
		return -1;
	}

	p->status = READY;
	p->ppid = running->pid;
	p->parent = running;
	p->priority = running->priority;

	for ( i=1; i<10; i++ )
	{
		p->kstack[SSIZE-i] = 0;
	}

	p->ksp = &(p->kstack[SSIZE - 9]);

	p->kstack[SSIZE-1] = (int)goUmode;
	
   for (i=0; i<NFD; i++){
      p->fd[i] = running->fd[i];
      if (p->fd[i] != 0){
          p->fd[i]->refCount++;
          if (p->fd[i]->mode == READ_PIPE)
              p->fd[i]->pipe_ptr->nreader++;
          if (p->fd[i]->mode == WRITE_PIPE)
	      p->fd[i]->pipe_ptr->nwriter++;
      }
   }

	enqueue(&readyQueue, p);
	nproc++;

	segment = (p->pid + 1) * 0x2000;

	for(i = 0; i < 0x2000; i++) 
	{
		put_word( get_word( from_segment, i ), segment, i );
	}

	for (i = 1; i < 13; ++i)
	{
		switch(i) 
		{
			case 1:   wurd = 0x0200;  break;  // uFlag
			case 2:
			case 11:
			case 12:  wurd = segment; break;  // uCS, uES, uDS
			case 10: put_word(0, segment, 0x2000-i*2); continue;
			default:  wurd = 0;       break;  // pretty much everything else
		}

		put_word(wurd, segment, 0x2000-i*2);  // stack starts at highest end of segment
	}

	p->uss = segment;
	p->usp = 0x2000-24;

	put_word(0, segment, running->usp + 8*2);

	printf("[%d] forked [%d]: %x\n", running->pid, p->pid, segment);

	return p->pid;
}
コード例 #30
0
ファイル: queuetest.c プロジェクト: ChukaEbi/queue-node-test
/**
 * main function for testing the queue
 */
int main() {
	int max_cells = 3;
	Foo2 f1;
	f1.x = 1;
	f1.y = 1.01;

	Foo2 f2;
	f2.x = 2;
	f2.y = 2.02;

	Foo2 f3;
	f3.x = 3;
	f3.y = 3.03;

	Foo2 *f;
	Queue *new_queue = create_queue(max_cells);
	printf("dequeue\n");
	void *testforemptyqueue = dequeue(new_queue);
	if (testforemptyqueue == NULL) {
		printf("empty test pass\n");
	} else {
		printf("%d\n", testforemptyqueue);
	}
	printf("enqueue 1 1.01\n");
	enqueue(new_queue, &f1);
	f = (Foo2*) dequeue(new_queue);
	printf("dequeue %d %f\n", f->x, f->y);

	printf("enqueue 1 1.01\n");
	enqueue(new_queue, &f1);
	printf("enqueue 2 2.02\n");
	enqueue(new_queue, &f2);
	f = (Foo2*) dequeue(new_queue);
	printf("dequeue %d %f\n", f->x, f->y);
	f = (Foo2*) dequeue(new_queue);
	printf("dequeue %d %f\n", f->x, f->y);

	printf("enqueue 1 1.01\n");
	enqueue(new_queue, &f1);
	printf("\n");

	printf("enqueue 2 2.02\n");
	enqueue(new_queue, &f2);
	printf("\n");	

	f = (Foo2*) dequeue(new_queue);
	printf("dequeue %d %f\n", f->x, f->y);

	printf("enqueue 3 3.03\n");
	enqueue(new_queue, &f3);
	f = (Foo2*) dequeue(new_queue);
	printf("dequeue %d %f\n", f->x, f->y);
	f = (Foo2*) dequeue(new_queue);
	printf("dequeue %d %f\n", f->x, f->y);

	printf("enqueue 1 1.01\n");
	enqueue(new_queue, &f1);
	printf("enqueue 2 2.02\n");
	enqueue(new_queue, &f2);
	printf("enqueue 3 3.03\n");
	enqueue(new_queue, &f3);
	printf("enqueue 1 1.01\n");
	int result = enqueue(new_queue, &f1);
	printf("%d\n", result);

	print_dequeue(dequeue(new_queue));
	printf("enqueue 1 1.01\n");
	enqueue(new_queue, &f1);
	print_dequeue(dequeue(new_queue));
	print_dequeue(dequeue(new_queue));
	print_dequeue(dequeue(new_queue));
	return 0;
}