PDA

View Full Version : درخواست راهنمایی در مورد برنامه پارکینگ



clapton
چهارشنبه 20 دی 1391, 14:57 عصر
سلام دوستان.من یک برنامه نوشتم که کلید های S,E, رو برای خروج و ورود ماشین ها و کلید F رو برای توقف سیستم تعریف کردم .راستش برنامه رو پله به پله نوشتم و تو مرحله اول کلید F کار میکرد اما وقتی دستورات سمافر رو اضافه کردم و برنامه رو کامل کردم دیگه این کلید کار نمیکنه .از استادم پرسیدم گفت به دلیل اینه که باید اول اجرای Thread های دیگه رو متوقف کنی.گفت که به دلیل sem_wait این مسئله پیش میاد و باید اول با یه دستوری متوقفش کنی تا کلید F بتونه کار کنه.خلاصه که الان خیلی گیج شدم و نمیدونم باید چیکارش کنم.راستی برنامه تحت سیستم های unix نوشته شده و تو ویندوز اجرا نمیشه.ممنون میشم اگه یه راهنمایی در این مورد انجام بدین.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <pthread.h>
#include<semaphore.h>

#define TRUE 1
#define FALSE 0

int places=10;
sem_t evt_in,evt_out,evt_maj;
int fin=FALSE;
pthread_mutex_t mutex_pl;
pthread_cond_t cond_places ;

void * t_keyboard (void *arg)
{
char res;
while (fin!=TRUE)
{
res=getchar();
//fflush(stdin);
//printf ("user input=%c\n",res);
if(res=='f')
{
fin=TRUE;
}
else if ( res=='e')
{
sem_post(&evt_in);
}
else if (res=='s')
{
sem_post(&evt_out);
}
}
}
void * t_enter (void *arg){
while (fin!=TRUE){
//printf("ok t enter\n");
sem_wait(&evt_in);
// printf("ok t enter\n");
pthread_mutex_lock(&mutex_pl);
if (places==0){
pthread_cond_wait(&cond_places, &mutex_pl);
}
printf(" barrier opening(IN)");

places = places -1;
sem_post(&evt_maj);
// printf(" ok t enter\n");
pthread_mutex_unlock(&mutex_pl);
}
}
void * t_exit (void *arg){

while (fin!=TRUE){
sem_wait(&evt_out);
pthread_mutex_lock(&mutex_pl);
if (places==0){
pthread_cond_wait(&cond_places, &mutex_pl);
}
printf("barrier opening IN");
places = places +1;
sem_post(&evt_maj);
pthread_mutex_unlock(&mutex_pl);
}
}
void * t_display (void *arg){

while (fin!= TRUE) {
sem_wait(&evt_maj);
pthread_mutex_lock(&mutex_pl);
printf ("places = %d\n",places);
pthread_mutex_unlock(&mutex_pl);
}
}

int main()
{

pthread_t thread_keyboard,thread_enter,thread_display,thread _exit;
int ikeyboard,ienter,idisplay,iexit;
pthread_mutex_init(&mutex_pl,NULL);
pthread_cond_init(&cond_places,0);
sem_init(&evt_in,0,0);
sem_init(&evt_maj,0,0);

ikeyboard=pthread_create( &thread_keyboard, NULL,&t_keyboard,NULL);
ienter=pthread_create( &thread_enter, NULL,&t_enter,NULL);
iexit=pthread_create( &thread_exit, NULL,&t_exit,NULL);
idisplay=pthread_create( &thread_display, NULL,&t_display,NULL);

pthread_join( thread_keyboard, NULL);
pthread_join( thread_enter, NULL);
pthread_join( thread_exit, NULL);
pthread_join( thread_display, NULL);

exit(0);
}