简体   繁体   中英

Initializing an array of structs for usage with pthreads

I am trying to get a p_threads program to work using the GMP struct mpz_class :

int main(){

    pthread_t* threads = (pthread_t*)malloc(thread_count * sizeof(pthread_t));

    data* results_n_params = (data*)malloc(thread_count * sizeof(*results_n_params));

    int thread_count = 10;
    unsigned long start = 1;
    unsigned long end = 100;
    unsigned long batch_size = 10;
    for(int i = 0; i < thread_count; i++){  
        // Set parameters of results struct.
        results_n_params[i].start = start + i * batch_size;
        results_n_params[i].end = start + (i + 1) * batch_size;
        pthread_create(&threads[i], NULL, add_part, (void*) &results_n_params[i])
}

This is the struct:

typedef struct {
    unsigned long start;
    unsigned long end;
    mpz_class result;
} data;

And here is the thread body:

void *do_things(void* data_struct){
    data* current_data = (data*) data_struct;
    mpz_class result = 0;
    current_data->result = result; // <= This results in Bus error: 10
    return NULL;
}

The problem probably lies with the initialization of the results_n_params array. The thread_count variable is given as input (jsut changed it to be static here for shorter code) When changing thread_count around or increasing the size that gets allocated I can avoid the bus error: 10 I get when accessing mpz_class result . Like this I get a Bus Error: 10 for thread_size between 1 and 10. 10 And higher works fine. What am I doing wrong?

I don't see where threadcount is declared. It's value is set after memory allocation where that value is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM