PThread初始化2D数组

时间:2019-06-10 15:10:24

标签: c arrays pthreads

我尝试用四个pthread初始化2d数组的边界(北,东,南,西)。我的代码如下:

#define M 500
#define N 500
#define NUM_THREADS 4
double plate[M][N];
pthread_t threads[NUM_THREADS];

void *initBorder(void *arg) {
    int index = *((int *) arg);
    switch (index) {
        case 0:
            for (int i = 0; i < N; i++ ) { plate[0][i] = 0; }
            break;
        case 1:
            for (int i = 1; i < M-1; i++) { plate[i][N-1] = 100; }
            break;
        case 2:
            for (int i = 0; i < N; i++) { plate[M-1][i] = 100; }
            break;
        default:
            for (int i = 1; i < M-1; i++) { plate[i][0] = 100; }
            break;
    }
    return NULL;
}

int main() {
    double plate[M][N];

    for (int i = 0; i < NUM_THREADS; i++) {
        printf("Thread %d created\n", i);
        pthread_create(&threads[i], NULL, initBorder, (void *) &i);
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
    printf("Threads joined\n");
    printPlate();

    return 0;
}

问题是,有时我只会得到我期望的结果(以zero进行North初始化,以100的值休息)。也许有人可以帮助我。

非常感谢您。

0 个答案:

没有答案