2012-11-21 171 views
4

我正在遵循一个示例来实现C中的线程:http://ramcdougal.com/threads.html。 本例使用一维数组。我需要一个动态的二维数组。二维数组指针

如果在main()这是int **array而不是int array[ARRAYSIZE],它会是什么样子?

我的问题是如何将指针传递给结构的二维数组。 这个想法是,我有一个大数组,每个线程应该只填充该数组的某个区域。

非常感谢!

下面是从示例代码:

struct ThreadData { 

    int start, stop; 
    int* array; 

}; 


void* squarer(struct ThreadData* td) { 


    struct ThreadData* data=(struct ThreadData*) td; 
    int start=data->start; 
    int stop=data->stop; 
    int* array=data->array; 
    int i; 

    for (i=start; i<stop; i++) { 
     array[i]=i*i; 
    } 

    return NULL; 
} 

int main(void) { 

    int array[ARRAYSIZE]; 
    pthread_t thread[NUMTHREADS]; 
    struct ThreadData data[NUMTHREADS]; 
    int i; 

    int tasksPerThread=(ARRAYSIZE+NUMTHREADS-1)/NUMTHREADS; 

    for (i=0; i<NUMTHREADS; i++) { 
     data[i].start=i*tasksPerThread; 
     data[i].stop=(i+1)*tasksPerThread; 
     data[i].array=array; 
    } 
    /* the last thread must not go past the end of the array */ 
    data[NUMTHREADS-1].stop=ARRAYSIZE; 

    /* Launch Threads */ 
    for (i=0; i<NUMTHREADS; i++) { 
     pthread_create(&thread[i], NULL, squarer, &data[i]); 
    } 

    /* Wait for Threads to Finish */ 
    for (i=0; i<NUMTHREADS; i++) { 
     pthread_join(thread[i], NULL); 
    } 

    /* Display Result */ 
    for (i=0; i<ARRAYSIZE; i++) { 
     printf("%d ", array[i]); 
    } 
    printf("\n"); 

    return 0; 
} 

回答

1

认为它是这样的:

当具有一个维阵列的工作,startstop是表示在1-d空间中的坐标的一个维向量(一维矢量可以用一个整数表示,这就是原始代码所使用的整数)。

所以在一个二维数组中,startstop应该是二维矢量:

struct ThreadData 
{ 
    int start[2], stop[2]; 
    int **array; 
} 

然后,你的线程之间分割的矩形块。并且每个线程在start中获取其块左上角的位置,并在stop中获取其块右下角的位置。

enter image description here

记住,块,矩形,可以是高带(每线程1列),或长(每线程一行),或正方形,或两者之间的任何地方。通过基准测试,您必须确定哪种形状可以更快速地工作。

从某种意义上说,tasksPerThread也有两个维度。随着任务的实际数量变为tasksPerThread[0] * tasksPerThread[1]

+0

非常感谢!说得通 ! – user1841373

4

动态分配二维数组中使用这样的:

int** array = malloc(sizeof(int*)*ARRAYSIZE); 

在这里,您分配一个指针数组为int,现在你应该知道为每个指针分配内存:

for(int i = 0;i<ARRAYSIZE;i++) 
    array[i] = malloc(sizeof(int)*INNER_ARRAYSIZE); 

现在填写每个条目与您的ctual数据:

for(int i = 0;i<ARRAYSIZE;i++) 
    for(int j = 0;j<INNER_ARRAYSIZE;j++) 
     array[i][j]=(i+j);//just for example 

并更新ThreadData结构使用二维数组:

struct ThreadData { 

int start, stop; 
int** twoDimArray;//note one more * here 

};

而只是通过指针的位置:

struct ThreadData data; 
data.twoDimArray = array; 
data.twoDimArray[0][0] = data.twoDimArray[0][0]*data.twoDimArray[0][0]; //access element at 0,0 and square it 
+0

这样做会使所有数据不连续,从而使您的缓存性能较差。更好地使用Iliffe矢量策略。 –

+0

主题首发试图遵循简单的教程,让我们现在只保留所有可怕的C东西:) –

+0

非常感谢。作品! – user1841373