간단한 FIFO queue 예제

Posted at 2010/04/22 08:35 // in Programming // by Daniel

#include <stdio.h>

static char qout( void );
static int qin( char in );
static int  qlen ( void );
#define Q_MAX   4
int queue[Q_MAX];
int qhead=0;
int qtail=0;
int main(void)
{
    char io;
    char input;
    int exit=0;
    int state=0;
    char rd;
    printf("simple queue test\n");
    fflush(stdin);
    do {
        switch(state) {
            case 0:
                printf("cmd $ ");
                state = 1;
            case 1:
                fflush(stdout);
                fflush(stdin);
                rd = getchar();
                if (rd==' ' || rd=='\n')
                    continue;
                if (rd=='q') {
                    exit=1;
                    break;
                }
                // get cmd;
                if (rd=='i')
                    state = 5;
                if (rd=='o')
                    state = 10;
                break;
            case 5:
                // input
                printf("input$ ");
                state = 6;
            case 6:
                fflush(stdout);
                fflush(stdin);
                rd = getchar();
                if (rd==' ' || rd=='\n')
                    continue;
                if (rd=='q') {
                    exit=1;
                    break;
                }
                input = rd;
                qin(input);
                printf("h=%d, tail=%d qlen=%d\n", qhead, qtail, qlen());
                state = 0;
                break;
            case 10:
                // get

                printf("%c\n", qout());
                printf("h=%d, tail=%d qlen=%d\n", qhead, qtail, qlen());
                state = 0;
                break;
            default:
                printf("default state??\n");
                exit=1;
        } // switch
    } while(!exit);

    return 0;
}

static int  qlen ( void )
{
    if ( qhead >= qtail )
        return qhead-qtail;
    return qhead+Q_MAX+1-qtail;
}

static int qin( char in )
{
    int tmp_head = qhead;
    tmp_head++;
    if (tmp_head==(Q_MAX+1))
        tmp_head=0;
    if (tmp_head==qtail) {
        // overrun
        fprintf(stderr, "q overrun\n");
        return -1;
    }
    printf("q[%d]<:=%c\n", qhead, in);
    queue[qhead] = in;
    qhead = tmp_head;
    return 0;
}

static char qout( void )
{
    int tmp_tail = qtail;
    if (qtail == qhead) {
        // underrun
        fprintf(stderr, "q underrun\n");
        return '\b';
    }
    qtail = (tmp_tail +1 );
    if (qtail == (Q_MAX+1))
        qtail = 0;
    printf("q[%d]==%c\n", tmp_tail, queue[tmp_tail]);
    return queue[tmp_tail];
}

리팩토링 필요 – 리팩토링 했지만 여기에 게시하진 않음.
크리에이티브 커먼즈 라이센스
Creative Commons License