【问题标题】:Seg Fault in pthread_mutex_init() [closed]pthread_mutex_init()中的段错误[关闭]
【发布时间】:2014-03-04 20:54:41
【问题描述】:

我需要在具有不同粒度级别的 NxN 矩阵上加锁。初始化网格级锁时,我在 pthread_mutex_init() 函数中遇到分段错误。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>

#define MAXGRIDSIZE     10
#define MAXTHREADS      1000
#define NO_SWAPS        20
#define MIN(X,Y)        ((X < Y) ? X : Y)
#define MAX(X,Y)        ((X > Y) ? X : Y)

extern int errno;

typedef enum {GRID, ROW, CELL, NONE} grain_type;
const int gridsize = 0;
int grid[MAXGRIDSIZE][MAXGRIDSIZE];
int threads_left = 0;
time_t start_t, end_t;

pthread_mutex_t grid_lock;
pthread_mutex_t *row_lock;
pthread_mutex_t **cell_lock;

int main(int argc, char **argv)
{
        printf("GOOD\n");

        int nthreads = 0;
        pthread_t threads[MAXTHREADS];
        grain_type rowGranularity = NONE;
        long initSum = 0, finalSum = 0;
        int i,j;

        printf(" arg[0]:%s \n arg[1]:%s \n arg[2]:%s \n arg[3]:%s \n",argv[0], argv[1], argv[2], argv[3]);

        /*get dimensions for n x n matrix*/
        int gridsize = atoi(argv[1]);

        printf("PAST atoi\n");

        pthread_mutex_init(&grid_lock,NULL);

        printf("grid_lock initialized");

        row_lock = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)*gridsize);

        for(i = 0; i < gridsize; i++){
            pthread_mutex_init(&row_lock[i],NULL);
        }

        cell_lock = malloc(sizeof(pthread_mutex_t*)*gridsize);

        for(i = 0; i < gridsize; i++){
            cell_lock[i] = malloc(sizeof(pthread_mutex_t)*gridsize);

            for(j = 0; j < gridsize; i++)
                pthread_mutex_init(&cell_lock[i][j],NULL);
        }

错误在“pthread_mutex_init(&grid_lock,NULL);”这一行根据 GDB 和周围的 printf 语句。我查看了几个朋友的代码几乎相同,但他们没有任何问题。我完全迷失了解决方案。

【问题讨论】:

    标签: c synchronization segmentation-fault pthreads mutex


    【解决方案1】:

    您的内部循环使用了错误的增量器:

    for(j = 0; j < gridsize; i++)
    // this -----------------^
    

    应该是这样的:

    for(j = 0; j < gridsize; j++)
    // that -----------------^
    

    哦,剪切和粘贴,你是一个残酷无情的小妞。

    【讨论】:

    • 可能应该提到这一点,投票关闭,因为这显然是一个错字,但至少你现在知道为什么了。
    • 同意。并添加 OP 对错误发生位置的误解的原因:如果 printf("grid_lock initialized"); 将是 printf("grid_lock initialized\n");,则日志消息不会卡在 stdout 的缓冲区中,而是被打印出来,很明显not 在“周围的 printf statements*”中的错误。经验教训:总是fprintf() 调试消息发送到stderr,因为默认情况下它是无缓冲的。
    • 是的,我意识到错字并修复了所有代码。现在工作正常。感谢您提供有关调试语句的提示!至少我从我的愚蠢错误中获得了一些知识。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    相关资源
    最近更新 更多