初始化用于pthread的结构体数组

Initializing an array of structs for usage with pthreads

本文关键字:结构体 数组 pthread 用于 初始化      更新时间:2023-10-16

我正在尝试使用GMP结构mpz_class获得p_threads程序:

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])
}

结构体:

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

下面是线程体:

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;
}

问题可能在于results_n_params数组的初始化。thread_count变量作为输入(只是将其更改为静态,以便更短的代码)当更改thread_count周围或增加分配的大小时,我可以避免访问mpz_class result时获得的bus error: 10。像这样,我得到thread_sizeBus Error: 10在1和10之间。高一点也行。我做错了什么?

我不知道threadcount是在哪里声明的。