初始化一个结构数组以供pthreads使用

时间:2015-10-24 16:10:37

标签: c++ pthreads gmp

我正在尝试使用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变量作为输入给出(对于更短的代码,jsut将其更改为静态)当更改thread_count或增加分配的大小时,我可以避免我得到的bus error: 10访问mpz_class result。像这样我得到Bus Error: 10 thread_size介于1和10之间.10更高的工作正常。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我没有看到宣布threadcount的位置。在使用该值的内存分配之后设置它的值。