head	1.0;
access;
symbols;
locks
	ntcommon:1.0; strict;
comment	@ * @;


1.0
date	95.12.17.19.47.28;	author ntcommon;	state Exp;
branches;
next	;


desc
@This is the first working netrek version, plasmas and other special weapons do not work.
@


1.0
log
@Initial revision
@
text
@/* 
 * findslot.c
 *
 * Kevin Smith 03/23/88
 * Heavily modified my Michael Kantner 10/94
 *
 */
#include "copyright2.h"

#include <stdio.h>
#include <sys/types.h>
#include "defs.h"
#include "struct.h"
#include "data.h"

/* Some prototypes to silence the linker */
struct queuewait *queue_add();


/*
 * The following code for findslot() is really nice.
 *
 * Returns either the player slot number or -1 if it cannot give a slot.
 *
 * Every process will wait for a second (sleep(1)), and then check the queue
 *   status, do what is appropriate, and repeat.
 *
 * Variables:
 *   queue->count:  (shared mem) Next number to take.
 *
 *   oldcount:      (local) My position last time I looked.
 */

int findslot(w_queue)
int w_queue;   /* Index of used wait queue */
{
    u_int oldcount;	/* My old number */
    pid_t mypid = getpid();
    int i;		
    int rep = 0;
    struct queuewait *mywait = NULL;
    
    /* Ensure that the queue is open */
    if (!(queues[w_queue].q_flags & QU_OPEN)) return (-1);

    /* If no one is waiting, I will try to enter now */
    if (queues[w_queue].first == NULL)
	if ( (i=pickslot(w_queue)) >= 0 )  return (i);

    mywait = queue_add(w_queue);        /* Get me into the queue */
    if (mywait == NULL) return (-1);    /* The queue is full! */

    oldcount = mywait->count;

    for (;;) {
        /* Check to ensure that the player still owns his wait slot */
        if (mypid != mywait->process){
          ERROR(1,("findslot: process lost its waitq entry!\n"));
          mywait = queue_add(w_queue);        /* Get me into the queue */
          if (mywait == NULL) return (-1);    /* The queue is full! */
          /* The count should change, so a new packet will be sent. */
      }

	/* If we are first in line, check for a free slot */
	if (mywait == queues[w_queue].first){
	    if ((i=pickslot(w_queue)) >= 0 ) {
		queue_exit(mywait);
		return (i);
	    }
	} /* End of if I am first in line */

	/* Send packets occasionally to see if he is accepting... */
	if (rep++ % 10 == 0) {
	    sendQueuePacket((short) mywait->count);
	}
	
	if (isClientDead()) {
	    queue_exit(mywait);
	    fflush(stderr);
	    exit(0);
	}

	if (mywait->count != oldcount) {  /* If my count changed */
	    sendQueuePacket((short) mywait->count);
	    oldcount=mywait->count;
	}

	/* Message from daemon that it died (is going down) */
	if (status->gameup == 0) {
	    queue_exit(mywait);
	    return (-1);
	}

	/* To mimize process overhead and aid synchronization */
	sleep(1);

    }
    return -1;
}
@
