簡體   English   中英

C-使用互斥和線程的分段錯誤

[英]C - Segmentation fault using mutex and threads

我正在使用線程和互斥鎖。 但是由於某些原因,我不知道為什么,但是遇到了一些分段錯誤。 無法使用gdb,因為我無法獲取該錯誤= /

我也嘗試在行之間進行一些打印,但看不到任何相關信息...

有人可以告訴我為什么會這樣嗎?

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

// Not order for easy random implementation
#define CITY_B 1
#define CITY_A 2
#define CITY_C 3
#define CITY_D 4
#define TRAIN_NUMBER 3

pthread_mutex_t lineAB;
pthread_mutex_t lineBC;
pthread_mutex_t lineBD;

typedef struct {
    int num;
    int from;
    int to;
}Train;

int generateRandom(int min, int max, int seed) {
    srand(time(NULL)+seed);
    return ((rand()%max)+min);
}

char * getCurrentTime() {
    char * timeString = (char *) malloc(sizeof(char) * 20);
    time_t now = time(NULL);
    strftime(timeString, 20, "%H:%M:%S", localtime(&now));
    return timeString;
}

char * hora() {
    return getCurrentTime();
}

pthread_mutex_t * nextLine(int from, int to) {
    switch(from) {
        case CITY_A: {
            return &lineAB;
        }
        case CITY_B: {
            switch(to) {
                case CITY_A: {
                    return &lineAB;
                }
                case CITY_C: {
                    return &lineBC;
                }
                case CITY_D: {
                    return &lineBD;
                }
            }
            break;
        }
        case CITY_C: {
            return &lineBC;
        }
        case CITY_D: {
            return &lineBD;
        }
    }
}

char * getCityName(int num) {
    switch(num) {
        case CITY_A: {
            return "City A";
        }
        case CITY_B: {
            return "City B";
        }
        case CITY_C: {
            return "City C";
        }
        case CITY_D: {
            return "City D";
        }
    }
}

char * getLineName(int from, int to) {
    switch(from) {
        case CITY_A: {
            return "cityA-cityB";
            break;
        }
        case CITY_B: {
            switch(to) {
                case CITY_A: {
                    return "cityA-cityB";
                    break;
                }
                case CITY_C: {
                    return "cityB-cityC";
                    break;
                }
                case CITY_D: {
                    return "cityB-cityD";
                    break;
                }
            }
            break;
        }
        case CITY_C: {
            return "cityB-cityC";
            break;
        }
        case CITY_D: {
            return "cityB-cityD";
            break;
        }
    }
}

void * threadFunc(void *arg){
    Train * train = (Train*)arg;
    /*int trainNum = info[0];
    int from = info[1];
    int to = info[2];*/
    char * partida = hora();
    char * chegada;

    printf("Train %d, From: %s, To: %s\n", train->num, getCityName(train->from), getCityName(train->to));

    //printf("A\n");
    pthread_mutex_t * myMutex = nextLine(train->from, CITY_B);
    pthread_mutex_lock(myMutex);
    //printf("B\n");
    printf("Train: %d\tLine: %s\tFrom: %s\tTo: %s\n", train->num, 
        getLineName(train->from, CITY_B), getCityName(train->from), getCityName(train->to));
    // Each line takes x sec to finish
    //printf("C\n");
    sleep(3);
    //printf("D\n");
    pthread_mutex_unlock(myMutex);
    //printf("E\n");
    myMutex = nextLine(CITY_B, train->to);
    //printf("F\n");
    printf("Train: %d\tLine: %s\tFrom: %s\tTo: %s\n", train->num, 
        getLineName(CITY_B, train->to), getCityName(train->from), getCityName(train->to));
    // Each line takes x sec to finish
    //printf("G\n");
    sleep(3);
    //printf("H\n");
    pthread_mutex_unlock(myMutex);
    //printf("I\n");
    chegada = hora();
    //printf("J\n");
    printf("\nTrain: %d\nDeparture: %s\tArrival: %s\n\n", train->num, partida, chegada);
    //printf("K\n");
    pthread_exit((void*)NULL);
}

int main(char *arg, char **args){
    pthread_t threads[TRAIN_NUMBER];
    Train trains[TRAIN_NUMBER];

    lineAB = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
    lineBC = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
    lineBD = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;

    srand(time(NULL));
    int i;
    for (i = 0; i < TRAIN_NUMBER; ++i) {
        trains[i].num = i+1;
        trains[i].from = generateRandom(CITY_A, CITY_D, i);
        if(trains[i].from == CITY_A) {
            trains[i].to = generateRandom(CITY_C, CITY_D, i);
        } else {
            trains[i].to = CITY_A;
        }
        pthread_create(&threads[i],NULL,threadFunc,(void*)&trains[i]);
    }

    for(i = 0; i < TRAIN_NUMBER; i++) {
        pthread_join(threads[i], NULL);
    }

    pthread_mutex_destroy(&lineAB);
    pthread_mutex_destroy(&lineBC);
    pthread_mutex_destroy(&lineBD);

    return 0;
}

這是代碼的一些結果!

示例1(打印任何內容之前):

make: *** [run] Segmentation fault

范例2:

Train 1, From: City D, To: City A
Train: 1    Line: cityB-cityD   From: City D    To: City A
Train 3, From: City D, To: City A
make: *** [run] Segmentation fault

范例3:

Train 1, From: City A, To: City C 
Train: 1    Line: cityA-cityB   From: City A    To: City C
Train 2, From: City A, To: City C
Train 3, From: City C, To: City A
Train: 3    Line: cityB-cityC   From: City C    To: City A
Train: 1    Line: cityB-cityC   From: City A    To: City C
Train: 3    Line: cityA-cityB   From: City C    To: City A
Train: 2    Line: cityA-cityB   From: City A    To: City C
Train: 2    Line: cityB-cityC   From: City A    To: City C

Train: 1 Departure: 18:51:55    Arrival: 18:52:01

Train: 3 Departure: 18:51:55    Arrival: 18:52:01

Train: 2 Departure: 18:51:55    Arrival: 18:52:04

我用

ulimit -c無限

這導致生成核心文件。 現在可以運行gdb了。

調試此核心文件顯示錯誤在以下行:

printf("Train %d, From: %s, To: %s\n", train->num, getCityName(train->from), getCityName(train->to));

印刷火車給:

(gdb)打印*火車

$ 3 = {num = 3,從= 5,到= 2}

所以train-> from是無效的(有效值為1-4)!

train-> to和train-> from是通過generateRandom()生成的,因此該錯誤必須在此處。

int generateRandom(int min, int max, int seed) {
    srand(time(NULL)+seed);
    return ((rand()%max)+min);
}

rand()%max可以生成從0到max-1的數字。 將min添加到此可以得到max + min-1。 由於輸入是2(CITY_A)和4(CITY_D),因此您可以獲得2到5之間的數字。您可能想要這樣:

int generateRandom(int min, int max, int seed) {
    srand(time(NULL)+seed);
    return ((rand()%(max-min))+min);
}

已發布的代碼包含很多問題,大部分已在注釋中指出。

但是,主要問題是在此行的generateRandom()函數中:

return ((rand()%max)+min);

生成的值大於3(典型值為5)

然后,在代碼的后面,對互斥鎖數組的訪問將超出數組末尾。

然后,對pthread_mutex_lock()的調用被提供了無效的指針,從而導致seg故障事件。

gdb調試器的兩次傳遞以及對printf()一些“有用”調用迅速找到了問題的根源。

強烈建議您對調試器非常熟悉。

這是我用於調試的代碼版本:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h> // rand(), srand()
#include <unistd.h>

// Not order for easy random implementation
#define CITY_B 1
#define CITY_A 2
#define CITY_C 3
#define CITY_D 4
#define TRAIN_NUMBER 3

pthread_mutex_t lineAB = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lineBC = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lineBD = PTHREAD_MUTEX_INITIALIZER;

struct TrainStruct
{
    size_t num;
    size_t from;
    size_t to;
};

typedef struct TrainStruct Train;


size_t generateRandom(int min, int max, size_t seed)
{
    (void)seed;
    //srand(time(NULL)+seed);
    return (size_t)((rand()%max)+min);
}


char * getCurrentTime()
{
    char * timeString = malloc(20);
    time_t now = time(NULL);
    strftime(timeString, 20, "%H:%M:%S", localtime(&now));
    return timeString;
} // end function: getCurrentTime


char * hora() {
    return getCurrentTime();
}

pthread_mutex_t * nextLine(size_t from, size_t to)
{
    switch(from)
    {
        case CITY_A:
            return &lineAB;
            break;

        case CITY_B:
            switch(to)
            {
                case CITY_A:
                    return &lineAB;
                    break;

                case CITY_C:
                    return &lineBC;
                    break;

                case CITY_D:
                    return &lineBD;
                    break;

                default:
                    printf( "invalid  train.to: %lu\n", to);
                    return NULL;
                    break;
            } // end switch
            break;

        case CITY_C:
            return &lineBC;
            break;

        case CITY_D:
            return &lineBD;
            break;

        default:
            printf( "invalid  train.from: %lu\n", from);
            return NULL;
            break;
    } // end switch
}


char * getCityName(size_t num)
{
    switch(num)
    {
        case CITY_A:
            return "City A";
            break;

        case CITY_B:
            return "City B";
            break;

        case CITY_C:
            return "City C";
            break;

        case CITY_D:
            return "City D";
            break;

        default:
            printf( "invalid  city num: %lu\n", num);
            return NULL;
            break;
    } // end switch
}


char * getLineName( size_t from, size_t to)
{
    switch(from)
    {
        case CITY_A:
            return "cityA-cityB";
            break;

        case CITY_B:
            switch(to)
            {
                case CITY_A: {
                    return "cityA-cityB";
                    break;
                }
                case CITY_C:
                    return "cityB-cityC";
                    break;

                case CITY_D:
                    return "cityB-cityD";
                    break;

                default:
                    printf( "invalid  train.to: %lu\n", to);
                    return NULL;
                    break;
            } // end switch
            break;

        case CITY_C:
            return "cityB-cityC";
            break;

        case CITY_D:
            return "cityB-cityD";
            break;

        default:
            printf( "invalid  train.from: %lu\n", from);
            return NULL;
            break;
    } // end switch
}


void * threadFunc(void *arg)
{
    Train * train = (Train*)arg;
    /*int trainNum = info[0];
    int from = info[1];
    int to = info[2];*/
    char * partida = hora();
    char * chegada;

    // for testing
    printf( "func:%s\n num: %lu\n from: %lu\n to: %lu\n\n",
            __func__,
            train->num,
            train->from,
            train->to);

    printf("Train %lu, From: %s, To: %s\n\n",
        train->num,
        getCityName(train->from),
        getCityName(train->to));

    //printf("A\n");
    pthread_mutex_t * myMutex = nextLine(train->from, CITY_B);
    pthread_mutex_lock(myMutex);
    //printf("B\n");
    printf("Train: %lu\tLine: %s\tFrom: %s\tTo: %s\n",
        train->num,
        getLineName(train->from, CITY_B),
        getCityName(train->from),
        getCityName(train->to));

    // Each line takes x sec to finish
    //printf("C\n");
    sleep(3);
    //printf("D\n");
    pthread_mutex_unlock(myMutex);


    //printf("E\n");
    myMutex = nextLine(CITY_B, train->to);
    //printf("F\n");
    printf("Train: %lu\tLine: %s\tFrom: %s\tTo: %s\n",
        train->num,
        getLineName(CITY_B, train->to),
        getCityName(train->from),
        getCityName(train->to));

    // Each line takes x sec to finish
    //printf("G\n");
    sleep(3);
    //printf("H\n");
    pthread_mutex_unlock(myMutex);


    //printf("I\n");
    chegada = hora();
    //printf("J\n");
    printf("\nTrain: %lu\nDeparture: %s\tArrival: %s\n\n",
        train->num,
        partida,
        chegada);
    //printf("K\n");
    pthread_exit((void*)NULL);
}

int main( void )
{
    pthread_t threads[TRAIN_NUMBER];
    Train trains[TRAIN_NUMBER];



    srand((unsigned)time(NULL));

    for (size_t i = 0; i < TRAIN_NUMBER; ++i)
    {
        trains[i].num = i+1;
        trains[i].from = generateRandom(CITY_A, CITY_D, i);

        if(trains[i].from == CITY_A)
        {
            trains[i].to = generateRandom(CITY_C, CITY_D, i);
        }

        else
        {
            trains[i].to = CITY_A;
        }

        pthread_create(&threads[i],NULL,threadFunc,(void*)&trains[i]);
    }

    for(size_t i = 0; i < TRAIN_NUMBER; i++)
    {
        pthread_join(threads[i], NULL);
    }

    pthread_mutex_destroy(&lineAB);
    pthread_mutex_destroy(&lineBC);
    pthread_mutex_destroy(&lineBD);
} // end function: main

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM