当前位置: 首页>>代码示例>>C++>>正文


C++ enqueue函数代码示例

本文整理汇总了C++中enqueue函数的典型用法代码示例。如果您正苦于以下问题:C++ enqueue函数的具体用法?C++ enqueue怎么用?C++ enqueue使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了enqueue函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: InterruptHandler

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);
//.........这里部分代码省略.........
开发者ID:aaronsmooth,项目名称:scheduler-simulation-tcss422,代码行数:101,代码来源:cpu.c

示例2: handle

 // yield::EventHandler
 void handle(YO_NEW_REF Event& event) {
   enqueue(event);
 }
开发者ID:respu,项目名称:yield,代码行数:4,代码来源:event_queue.hpp

示例3: kfork

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);
}
开发者ID:dabbers,项目名称:dabos,代码行数:77,代码来源:t.c

示例4: main

// test
int main() {
  struct node* queue = new_queue();
  queue = enqueue(queue, 1);
  queue = enqueue(queue, 2);
  print_list(queue);
}
开发者ID:ericfischer,项目名称:misc,代码行数:7,代码来源:queue.c

示例5: set_current_worker

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();
    }
}
开发者ID:SunnyGyb,项目名称:rDSN,代码行数:71,代码来源:task.cpp

示例6: handle_client

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;	 
}
开发者ID:GPrathap,项目名称:MultiuserChatroomServer,代码行数:73,代码来源:chatroom.c

示例7: htonl

void OutPacketBuffer::enqueueWord(u_int32_t word) {
  u_int32_t nWord = htonl(word);
  enqueue((unsigned char*)&nWord, 4);
}
开发者ID:dalinhuang,项目名称:video-monitoring,代码行数:4,代码来源:MediaSink.cpp

示例8: enqueue

void OutPacketBuffer::useOverflowData() {
  enqueue(&fBuf[fPacketStart + fOverflowDataOffset], fOverflowDataSize);
  fCurOffset -= fOverflowDataSize; // undoes increment performed by "enqueue"
  resetOverflowData();
}
开发者ID:dalinhuang,项目名称:video-monitoring,代码行数:5,代码来源:MediaSink.cpp

示例9: stackPush

void stackPush(struct node **top,int x){
	enqueue(top,x); //push value to queue
	count++; //get no of elements added to queue
		
}
开发者ID:sanjeewa894,项目名称:Data-structure--322,代码行数:5,代码来源:quel.c

示例10: housekeep

void housekeep() {
    usb_task(); 	// service periodic usb functions
    while (usb_cdc_kbhit() && (nqueue(&rxque0) < HIBUF)) {
	enqueue(&rxque0, usb_cdc_getc());
    }
}
开发者ID:omnister,项目名称:velo,代码行数:6,代码来源:servo4.c

示例11: AllocateInputBuffer

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;
}
开发者ID:inn1983,项目名称:media-codec,代码行数:87,代码来源:FrameBufferManager.c

示例12: main

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;
}
开发者ID:neotaso,项目名称:pp,代码行数:61,代码来源:04D.c

示例13: dequeue


//.........这里部分代码省略.........
				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);
			}
		}
	}
}
开发者ID:aaronsmooth,项目名称:scheduler-simulation-tcss422,代码行数:101,代码来源:cpu.c

示例14: main

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;
}
开发者ID:divyar13,项目名称:DataStructures-Algos,代码行数:88,代码来源:Djikstra.c

示例15: kwsprep

/* 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);

//.........这里部分代码省略.........
开发者ID:00027jang27,项目名称:git,代码行数:101,代码来源:kwset.c


注:本文中的enqueue函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。