Ошибка сегментации (ядро сброшено) с несколькими потоками - PullRequest
0 голосов
/ 19 апреля 2019

Мы должны составить программу, которая имитирует функцию системы бронирования мест в театре. У нас есть N_cust клиенты, которые звонят в телефонный центр, и N_tel люди, которые отвечают на телефонные звонки. Каждый звонок длится от t_seathigh до t_seatlow секунд. Оплата кредитной картой прошла успешно с вероятностью P_cardsuccess. Программа получает два аргумента: количество клиентов и начальное число для rand_r. Для каждого клиента существует поток, и клиенты должны ждать, пока кто-нибудь из них заговорит по телефону. Моя проблема в том, что программа работает, но выдает ошибку сегментации или застревает в бесконечном цикле в первом цикле функции AwesomeThreadFunction.

Я подумал, что, возможно, я неправильно обработал переменную telefoners, поскольку программа иногда застревает в первом цикле функции, но я не знаю, как именно. Я также не знаю, почему я получаю эту ошибку сегментации. Где именно моя программа пытается получить доступ к нераспределенной памяти.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include "p3170013-p3170115-p3170097-res1.h"
#include <unistd.h>
#define N_seat 250
#define N_tel 8
#define N_seatlow 1
#define N_seathigh 5
#define t_seatlow 5
#define t_seathigh 10
#define P_cardsuccess 0.9
#define C_seat 20.0
#define BILLION 1E9

pthread_mutex_t lock_phone, lock_bank_account,lock_number_of_transfer,lock_wait_time, lock_service_time, lock_plan, lock_screen;
int plan[N_seat];
int phone_count=0,bank_account=0,tid=0,seats=0,telefoners=N_tel;
unsigned int seed;
float avg_wait_time=0,avg_service_time;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* AwesomeThreadFunction(void* vargc){
tid=*(int*)vargc;
struct timespec waitStart, waitEnd;
clock_gettime(CLOCK_REALTIME, &waitStart);
avg_wait_time-=(waitStart.tv_sec+waitStart.tv_nsec/BILLION);
pthread_mutex_lock(&lock_screen);
printf("%d\n",telefoners);
pthread_mutex_unlock(&lock_screen);
pthread_mutex_lock(&lock_phone);
while (telefoners == 0) {
    pthread_cond_wait(&cond, &lock_phone);
}
telefoners--;
pthread_mutex_unlock(&lock_phone);
pthread_mutex_lock(&lock_screen);
printf("coooooooool\n");
pthread_mutex_unlock(&lock_screen);
clock_gettime(CLOCK_REALTIME, &waitEnd);
avg_wait_time+=(waitEnd.tv_sec+waitEnd.tv_nsec/BILLION);
struct timespec talkStart, talkEnd;
clock_gettime(CLOCK_REALTIME, &talkStart);
int how_many_seats=rand_r(&seed);
seed=how_many_seats;
how_many_seats=how_many_seats%(N_seathigh-N_seatlow)+N_seatlow;
int how_many_seconds=rand_r(&seed);
seed=how_many_seconds;
how_many_seconds=how_many_seconds%(t_seathigh-t_seatlow)+t_seatlow;
sleep(how_many_seconds);
if(seats==N_seat){
    pthread_mutex_lock(&lock_screen);
    printf("%d Reservation cancelled because the theater is full\n",*(int*)vargc);
    pthread_mutex_unlock(&lock_screen);
}else if(seats+how_many_seats>N_seat){
    pthread_mutex_lock(&lock_screen);
    printf("%d Reservation cancelled because there are not enough seats available\n",*(int*)vargc);
    pthread_mutex_unlock(&lock_screen);
}else{       
    int c=0,i=0;
    pthread_mutex_lock(&lock_number_of_transfer);
    pthread_mutex_unlock(&lock_number_of_transfer);
    pthread_mutex_lock(&lock_plan);
    while(c<how_many_seats){
        if(!plan[i]){
            plan[i]=tid;
            c++;
        }
        i++;
    }
    seats+=how_many_seats;
    pthread_mutex_unlock(&lock_plan);
    int card_success=rand_r(&seed);
    seed=card_success;
    float tempp=(float)card_success/(float)RAND_MAX;
    card_success=(tempp<=P_cardsuccess);
    if(!card_success){
        pthread_mutex_lock(&lock_screen);
        printf("%d Reservation cancelled because the transaction with the credit card was not accepted\n",*(int*)vargc);
        pthread_mutex_unlock(&lock_screen);
        pthread_mutex_lock(&lock_plan);
        c=0;i=0;
        while(c<how_many_seats){
            if(plan[i]==tid){
                plan[i]=0;
                c++;
            }
            pthread_mutex_lock(&lock_screen);
            pthread_mutex_unlock(&lock_screen);
            i++;
        }
        seats-=how_many_seats;
        pthread_mutex_unlock(&lock_plan);
        pthread_mutex_lock(&lock_number_of_transfer);
        pthread_mutex_unlock(&lock_number_of_transfer);
    }else{
        pthread_mutex_lock(&lock_screen);
        printf("%d Reservation completed successfully.The number of the transaction is %d, your seats are ",*(int*)vargc,*(int*)vargc);
        pthread_mutex_unlock(&lock_screen);
        c=0;i=0;
        pthread_mutex_lock(&lock_plan);
        while(c<how_many_seats){
            if(plan[i]==*(int*)vargc){
                pthread_mutex_lock(&lock_screen);
                printf("%d ",i);
                pthread_mutex_unlock(&lock_screen);
                c++;
            }               
            i++;
        }
        pthread_mutex_unlock(&lock_plan);
        pthread_mutex_lock(&lock_screen);
        printf("and the cost of the transaction is %.2f euros\n",how_many_seats*C_seat);
        pthread_mutex_unlock(&lock_screen);
        pthread_mutex_lock(&lock_bank_account);
        bank_account+=how_many_seats*C_seat;
        pthread_mutex_unlock(&lock_bank_account);
    }
}
//we assume that the client is fully served when we have also printed out his/her result of the try to book seats
clock_gettime(CLOCK_REALTIME, &talkEnd);
double cow = ( talkEnd.tv_sec - talkStart.tv_sec ) + ( talkEnd.tv_nsec - talkStart.tv_nsec ) / BILLION;
pthread_mutex_lock(&lock_service_time);
avg_service_time+=cow;
pthread_mutex_unlock(&lock_service_time);
pthread_mutex_lock(&lock_phone);
telefoners++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock_phone);
pthread_exit(0);
}

int main(int argc,char* argv[]){
int i;
for(i=0;i<N_seat;i++){
    plan[i]    = 0;
}
//if user did not give the correct number of arguments
if(argc!=3){
    printf("Wrong number of arguments\n");
    return -1;
}

int N_cust=atoi(argv[1]),tel_available=N_tel,err;
i=0;
seed=atoi(argv[2]);
pthread_t *threads=(pthread_t*)malloc(N_cust*sizeof(pthread_t));
int threadid[N_cust];

//if we can't init one of the mutexes
pthread_mutex_init(&lock_phone, NULL);
pthread_mutex_init(&lock_bank_account, NULL);
pthread_mutex_init(&lock_number_of_transfer, NULL);
pthread_mutex_init(&lock_wait_time, NULL);
pthread_mutex_init(&lock_service_time, NULL);
pthread_mutex_init(&lock_plan, NULL);
pthread_mutex_init(&lock_screen, NULL);

//creating the threads
while(i<N_cust){
threadid[i]=i+1;
    err = pthread_create(&(threads[i]), NULL, AwesomeThreadFunction, (void*)&threadid[i]); //func name
    if (err){
        printf("Thread can't be created :[%s]\n", strerror(err));
    }
    i++;
}

//join the threads
void *status;
for (i = 0; i < N_cust; i++) {

    rc = pthread_join(threads[i], &status);

    if (rc != 0) {
        printf("ERROR: return code from pthread_join() is %d\n", rc);
        exit(-1);       
    }

    printf("Main: Thread %lu finished with status %d.\n", threads[i], *(int *)status);
}

//final output
for(i=0;i<N_seat;++i){
    if(plan[i]){
        printf("Seat %d / client %d\n",i+1,plan[i]);
    }
}
printf("Total revenue from sales:\t%d\n",bank_account);
printf("Average    waiting time:\t%f\n",(float)avg_wait_time/(float)N_cust);
printf("Average service time:\t%f\n",(float)avg_service_time/(float)N_cust);

free(threads);
//Destroy mutexes
pthread_mutex_destroy(&lock_phone);
pthread_mutex_destroy(&lock_bank_account);
pthread_mutex_destroy(&lock_number_of_transfer);
pthread_mutex_destroy(&lock_wait_time);
pthread_mutex_destroy(&lock_service_time);
pthread_mutex_destroy(&lock_plan);
pthread_mutex_destroy(&lock_screen);
pthread_cond_destroy(&cond);
return 0;
}

1 Ответ

0 голосов
/ 20 апреля 2019

Непосредственная проблема, приводящая к segfault, связана с (несущественные подробности опущены):

    if(seats+how_many_seats>N_seat) {
        ....
    } else {       
        int c=0,i=0;
        pthread_mutex_lock(&lock_plan);
        while(c<how_many_seats) {
            if(!plan[i]){
                plan[i]=tid;
                c++;
            }
            i++;
        }
        seats+=how_many_seats;
        pthread_mutex_unlock(&lock_plan);

Код определяет, может ли он удовлетворить запрос, и успешно переходит к резервированию мест.Только тогда это блокирует план.Между тем, между проверкой seats+how_many_seats>N_seat и блокировкой плана другой поток делает то же самое и модифицирует план.После этого доступно меньше мест, чем ожидает первый поток, и цикл while(c<how_many_seats) получает доступ plan за пределы.

Остальные я не проверял;Я ожидаю других подобных проблем.Нелетучие глобалы очень подозрительны.В любом случае, сделайте себе одолжение и используйте больше функций.

...