Параллельное программирование с использованием Pthreads

Я новичок в области параллельного программирования, поэтому решил поиграться с подпрограммой pthread_join(). Я придумал следующий код для вычисления a*X + Y, где a — скаляр, а X, Y — векторы некоторого размера.

Вот что я написал:

    #include <pthread.h>
    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>
    #define NUM_THREADS 4
    #define VECTOR_SIZE 65

    struct DAXPYdata
    {
      /* data */
      long a;
      long X[VECTOR_SIZE];
      long Y[VECTOR_SIZE];
    };

    struct DAXPYdata daxpystr;
    void *calcDAXPY(void *);

    int main(int argc, char *argv[])
    {
       int vec_index;

       /*Initialize vectors X and Y an scalar a*/
       daxpystr.a = 57;

    for(vec_index = 0 ; vec_index < 65 ; vec_index++){
        daxpystr.X[vec_index] = vec_index + 1;
        daxpystr.Y[vec_index] = vec_index + 2;
    }

    pthread_t call_thread[NUM_THREADS];
    pthread_attr_t attr;
    int flag;
    long i;
    void *status;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    for(i = 0;i < NUM_THREADS;i++){
        printf("In main() : Creating thread %ld \n", i);
        flag = pthread_create(&(call_thread[i]), &attr, calcDAXPY, (void *)i);
        if(flag == 0){
            printf("ERROR; return code from pthread_create() is %d\n", flag);
            exit(-1);
        }
    }   

    pthread_attr_destroy(&attr);
    for(i = 0; i < NUM_THREADS ; i++) {
       flag = pthread_join(call_thread[i], &status);
       if (flag) {
          printf("ERROR; return code from pthread_join() is %d\n", flag);
          exit(-1);
          }

       printf("main(): Completed join with thread %ld having a status of %ld\n", i, (long)status );
    }
    /* code */
    printf("main(): Program completed, exiting!\n");
    pthread_exit(NULL);
}

void *calcDAXPY(void *thread_id)
{
    int i;
    long tid;

    tid = (long)thread_id;

    printf("Thread %ld starting execution\n", tid);
    for(i = 0 ; i < VECTOR_SIZE ; i++){
        daxpystr.X[i] = daxpystr.a*daxpystr.X[i] + daxpystr.Y[i];
    }

    printf("Result of a*X + Y : ");
    for (i = 0; i < VECTOR_SIZE ; i++)
    {
        printf("%ld ", daxpystr.X[i]);
    }
    pthread_exit((void *)thread_id);
}

Приведенный выше код вызывает ошибку в подпрограмме pthread_create(), что приводит к выполнению одного потока. Ниже приведен вывод

In main() : Creating thread 0 
ERROR; return code from pthread_create() is 0
Thread 0 starting execution
Result of a*X + Y : 59 117 175 233 291 349 407 465 523 581 639 697 755 813 871 929 987 1045 1103 1161 1219 1277 1335 1393 1451 1509 1567 1625 1683 1741 1799 1857 1915 1973 2031 2089 2147 2205 2263 2321 2379 2437 2495 2553 2611 2669 2727 2785 2843 2901 2959 3017 3075 3133 3191 3249 3307 3365 3423 3481 3539 3597 3655 3713 3771 logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

Любые идеи о том, как разобраться с этим?


person Abhijeet Mohanty    schedule 28.12.2016    source источник
comment
Я не понимаю природы вашего замешательства. Как и многие функции библиотеки C, pthread_create() возвращает 0 в случае успеха. Это хорошо задокументировано. Вместо этого вы рассматриваете это как ошибку, и вы знаете, что считаете это ошибкой, потому что сообщение, которое вы отправляете, говорит вам об этом.   -  person John Bollinger    schedule 28.12.2016


Ответы (1)


В случае успеха pthread_create() возвращает 0

поэтому поток запускается, просто проверка кода ошибки должна выполняться наоборот:

if(flag != 0){
    printf("ERROR; return code from pthread_create() is %d\n", flag);
    exit(-1);
}
person Jean-François Fabre    schedule 28.12.2016