c - 多线程的段错误(核心转储)

标签 c multithreading segmentation-fault

我们必须制作一个程序来模拟剧院座位预订系统的功能。我们有 N_cust 客户调用电话中心,还有 N_tel 人员接听电话。每次通话持续时间从 t_seathight_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;
}

最佳答案

导致段错误的直接问题位于(省略不相关的细节):

    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越界。

其余的我没有检查;我预计还有其他类似的问题。非 volatile 全局变量非常可疑。无论如何,帮自己一个忙,使用更多的功能。

关于c - 多线程的段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764603/

相关文章:

c - 为什么我在运行程序时收到 "Segmentation Fault"?

c - 如何在不推送新堆栈帧的情况下溢出堆栈?

c - scanf 并非在每次循环迭代时都执行

c - 为什么我的二分搜索只能按此顺序处理 if 语句?

使用前的 C 声明

multithreading - 理解JVM的 "Attach Listener"线程

c# - 在多线程服务器应用程序中访问 SQL DB

c++ - 如何在 c 中转换 std::numeric_limits<float>::epsilon()?

python - 等待特定延迟后如何在python中启动线程

c++ - 我不明白 C++ 中的段错误