简体   繁体   English

初始化用于pthread的结构数组

[英]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 : 我正在尝试使用GMP struct 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])
}

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. 问题可能出在results_n_params数组的初始化上。 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 . 给出thread_count变量作为输入(在此处为短代码,jsut将其更改为静态)在更改thread_count或增加分配的大小时,我可以避免bus error: 10访问mpz_class result时得到。 Like this I get a Bus Error: 10 for thread_size between 1 and 10. 10 And higher works fine. 像这样,我会遇到一个Bus Error: 10 thread_size在1到10之间为thread_size及更高版本可以正常工作。 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. 在使用该值的内存分配后设置该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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