Home > Net >  Passing a result array into pthread_join
Passing a result array into pthread_join

Time:02-12

I have the below code but I'm not understanding why the results aren't printing out correctly. I'm allocating val to be the size of the number of results I want to acquire. I pass the address of the location in val that I want to save the results to.

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

void* roll_dice() {
    int value = (rand() % 6)   1;
    int* result = malloc(sizeof(int));
    *result = value;
    // printf("%d\n", value);
    printf("Thread result: %p\n", result);
    return (void*) result;
}

int main(int argc, char* argv[]) {
    int NUM_DICE = 4;
    srand(time(NULL));

    pthread_t th[NUM_DICE];

    for (int i  = 0; i < NUM_DICE; i  ) {
        if (pthread_create(&(th[i]), NULL, &roll_dice, NULL) == -1) {
            perror("failure");
        }
    }

    int* val = calloc(NUM_DICE, sizeof(int)); 
    for (int i = 0; i < NUM_DICE; i  ) {
        pthread_join(th[i], &val);          // this doesn't work
//      pthread_join(th[i], &(val i));      // this doesn't work        
        printf("%d\n", *val);
    }

    for (int i = 0; i < NUM_DICE; i  ) {
        printf("Dice %d rolled %d\n", i 1, *(val i));
    }

    return 0;
}

CodePudding user response:

  1. malloc returns void* if success, you need cast it to int*.

  2. the third parameter of pthread_create is void(*)(void*), not void(*)(), so the roll_dice() need a void* argument.

  3. we can use an array to store the threads return values.

  4. after all, we need to free the memory we used malloc allocted.

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

void* roll_dice(void*) {
    int value = (rand() % 6)   1;
    int* result = (int*)malloc(sizeof(int));
    *result = value;
    // printf("%d\n", value);
    printf("Thread result: %p\n", result);
    return (void*) result;
}

int main(int argc, char* argv[]) {
    int NUM_DICE = 4;
    srand(time(NULL));

    pthread_t th[NUM_DICE];

    for (int i  = 0; i < NUM_DICE; i  ) {
        if (pthread_create(&(th[i]), NULL, &roll_dice, NULL) == -1) {
            perror("failure");
        }
    }

    int* val[NUM_DICE];
    for (int i = 0; i < NUM_DICE; i  ) {
        pthread_join(th[i], (void**)&val[i]);          // this doesn't work
//      pthread_join(th[i], &(val i));      // this doesn't work        
        printf("%d\n", *val[i]);
    }

    for (int i = 0; i < NUM_DICE; i  ) {
        printf("Dice %d rolled %d\n", i 1, *(val[i]));
    }

    for (int i = 0; i < NUM_DICE; i  ) {
        free(val[i]);
    }

    return 0;
}
  • Related