警察小偷问题

2017-12-08  本文已影响0人  xmfaly

警察和小偷需要跑完200米距离,但两个人之间用一个3米的手铐铐住,请实现一个模型,用来描述警察和小偷跑步的情况。
(1)使用线程表现无序性。
(2)使用ncurse表现裕兴界面。
这是一个基本的生产者消费者模型。等待的条件是两人之间的距离不要超过3米。换句话说小偷在跑之前要判断是否小偷比警察的距离多3,如果是那小偷就不能再跑,就要等待警察进程跑。警察进程同样的道理。

完整代码

#include <stdio.h>          
#include <stdlib.h>
#include <time.h>
#include <curses.h>
#include "pthread.h"

//警察和小偷之间的距离
#define DISTANCE 3
//警察纵坐标
#define PY 10

//小偷纵坐标
#define TY 12


struct prodcons
{
    pthread_mutex_t lock;
    int polPos,thiefPos;
    pthread_cond_t notempty;
    pthread_cond_t notfull;
};

struct prodcons buffer;

void init(struct prodcons *b)
{
    pthread_mutex_init(&b->lock,NULL);
    pthread_cond_init(&b->notempty,NULL);
    pthread_cond_init(&b->notfull,NULL);
    b->polPos=0;
    b->thiefPos=0;

    //init ncurses
    initscr();
    crmode();
    noecho();

}

void prun(struct prodcons *b)
{
    pthread_mutex_lock(&b->lock);
    while(b->polPos - b->thiefPos >= DISTANCE)
    {
        printf("wait for t run\n");
        pthread_cond_wait(&b->notfull,&b->lock);
    }
    b->polPos++;

    clear();
    mvaddch(PY,b->polPos,'P');
    mvaddch(TY,b->thiefPos,'T');
    sleep(1);
    refresh();

    if(b->polPos == 200){
        printf("p run over\n");
        exit(0);
    }
    pthread_cond_signal(&b->notempty);
    pthread_mutex_unlock(&b->lock);
}

void trun(struct prodcons *b)
{
    pthread_mutex_lock(&b->lock);
    while( b->thiefPos -  b->polPos >= DISTANCE)
    {
      printf("wait for p run\n");
      pthread_cond_wait(&b->notempty,&b->lock);
    }
    b->thiefPos++;

    clear();
    mvaddch(TY,b->thiefPos,'T');
    mvaddch(PY,b->polPos,'P');

    clrtoeol();
    sleep(1);
    refresh();

    //printf("t poistion is %d\n", b->thiefPos);
    if(b->thiefPos == 200){
        printf("p run over\n");
        exit(0);
    }
    pthread_cond_signal(&b->notfull);
    pthread_mutex_unlock(&b->lock);
}

void * p()
{
    while(1)
    {
        prun(&buffer);
    }
    
    return NULL;
}

void * t()
{
    while(1)
    {
        trun(&buffer);
    }
    return NULL;
}

int main(void)
{
    pthread_t th_a,th_b;            
    void *retval;
    init(&buffer);
    pthread_create(&th_a,NULL,p,NULL);
    pthread_create(&th_b,NULL,t,NULL);
    pthread_join(th_a,&retval);
    pthread_join(th_b,&retval);
    endwin();
    return 0;
}

上一篇 下一篇

猜你喜欢

热点阅读