create thread - passing arguments

前端 未结 3 1001
清歌不尽
清歌不尽 2021-02-05 14:32

I am attempting on creating multiple threads that each thread calculates a prime. I am trying to pass a second argument to a function using thread create. It keeps throwing up e

3条回答
  •  遥遥无期
    2021-02-05 15:15

    You can only pass a single argument to the function that you are calling in the new thread. Create a struct to hold both of the values and send the address of the struct.

    #include 
    #include 
    typedef struct {
        //Or whatever information that you need
        int *max_prime;
        int *ith_prime;
    } compute_prime_struct;
    
    void *compute_prime (void *args) {
        compute_prime_struct *actual_args = args;
        //...
        free(actual_args);
        return 0;
    }
    #define num_threads 10
    int main() {
        int max_prime = 0;
        int primeArray[num_threads];
        pthread_t primes[num_threads];
        for (int i = 0; i < num_threads; ++i) {
            compute_prime_struct *args = malloc(sizeof *args);
            args->max_prime = &max_prime;
            args->ith_prime = &primeArray[i];
            if(pthread_create(&primes[i], NULL, compute_prime, args)) {
                free(args);
                //goto error_handler;
            }
        }
        return 0;
    }
    

提交回复
热议问题