警察和小偷需要跑完200米距離,但兩個人之間用一個3米的手銬銬住澎剥,請實現(xiàn)一個模型拘哨,用來描述警察和小偷跑步的情況谋梭。
(1)使用線程表現(xiàn)無序性。
(2)使用ncurse表現(xiàn)裕興界面倦青。
這是一個基本的生產者消費者模型瓮床。等待的條件是兩人之間的距離不要超過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;
}