我目前正在開發一個多線程程序來代表一個有n個學生的TA。當學生到達時,他們必須坐在走廊上的椅子上(在TA辦公室有3把椅子+ 1把椅子)。如果沒有更多的椅子,他們必須回家等待。多線程程序練習
這裏是我的代碼:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <pthread.h>
#include <unistd.h>
#include <stdbool.h>
#include <semaphore.h>
pthread_mutex_t mutex; /* mutex lock */
sem_t studentSem;
sem_t taSem;
int chairs = 1;
void *student(void *param);
void *ta(void *param);
int main(int argc, char* argv[]){
if(argc!=2){
fprintf(stderr, "Un nombre d'etudiant est requis en paramètre\n");
return -1;
}
if(atoi(argv[1])<0){
fprintf(stderr, "Un nombre d'etudiant >= 0 est requis\n");
return -1;
}else{
int numStudents = atoi(argv[1]);
int numThreads = numStudents + 1; /* n etudiant + 1 TA */
pthread_t tid[numThreads]; /* thread ID */
pthread_attr_t attr; /* thread attributes */
sem_init(&studentSem, 0, 1);
sem_init(&taSem, 0, 0); /* 0 car TA attend etudiant */
pthread_attr_init(&attr);
int i = 0;
pthread_create(&tid[i], &attr, ta, NULL); /*creer le TA*/
for (i = 1; i < numThreads; i++){
pthread_create(&tid[i], &attr, student, (void*)i); /*creer etudiant*/
}
for (i = 0; i < numThreads; i++){
pthread_join(tid[i], NULL);
}
}
return 0;
} /*fin du main*/
void *ta (void *param){ /*le thread pour TA*/
while(ta){
sem_post(&studentSem);
pthread_mutex_lock(&mutex);
chairs--;
pthread_mutex_unlock(&mutex);
printf("helping students\n");
sleep(rand()%(1+3));
sem_wait(&taSem);
}
}
void *student(void *param){
int *t;
t = (int *)param;
while(student){
if(chairs < 4){
pthread_mutex_lock(&mutex); /* protects chairs */
chairs++; /* incrementer chairs car etudiant prend cette chaise */
pthread_mutex_unlock(&mutex); /* releases mutex lock */
printf("%i is sitting down\n", t);
sem_post(&taSem); /* etudiant signal le TA pour demander de l'aide */
sem_wait(&studentSem); /* etudiant attend jusqua temps que TA l'aide et peut ensuite partir */
} else { /* no chairs available, so the student "goes home" */
printf("%i is going home\n", t);
sleep(rand()%(1+5)); /* sleeps a random amount of time */
}
}
}
我的問題是我不能讓它正常工作。當我使用運行在UNIX上「sleepingTA 5」的方案,它給了我以下結果:
1 is sitting down
1 is sitting down
1 is sitting down
1 is sitting down
2 is sitting down
3 is going home
4 is going home
5 is going home
5 is going home
1 is going home
1 is sitting down
...
環路總是無限的工作。我不知道如何改變它,所以在得到幫助後,學生離開......(不像第一名回來)。我需要學生只坐一次,連續不少次(如1),我需要學生回家一次,連續不少次(如5)...
什麼在你的代碼,你認爲停止同一個學生從一次又一次地坐下來? –
什麼都沒有......我試着說sem_post(&studentSem)來釋放它,但沒有奏效! – cditomas
請問什麼是「* TA *」?終端適配器? - ) – alk