pthread_mutex_init()中的段错误

时间:2014-03-04 20:54:42

标签: c synchronization segmentation-fault pthreads mutex

我需要将锁定放在具有不同粒度级别的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(&amp; grid_lock,NULL)”行中;“根据GDB和周围的printf语句。我查看了一些几乎相同的朋友代码,但他们没有任何问题。我完全迷失在一个解决方案上。

1 个答案:

答案 0 :(得分:2)

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

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

应该是这样的:

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

哦,切割和粘贴,你们是一个残酷而无情的笨蛋。