C通过引用传递结构

时间:2018-03-21 09:13:27

标签: c

struct Args{
    char *name;
    int counter;
};

void *Producer(void* args){
    struct Args *data = (struct Args*) args;
    //change counter value here which should be changed in main too
}

int main(){
    ...
    ...

    int counter = 0; //will be updated in Producer function
    struct Args args;
    args.counter = counter;
    args.name = "";
    pthread_create(&thread_id, NULL, Producer, &args);
    return 0;
}

我只能将struct传递给一个线程函数,我有一个计数器,我希望每个线程更新...我可以使它全局,但必须将其作为结构传递。我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

如果您需要从不同的线程引用本地变量,可以使用如下代码:

struct Args{
    char *name;
    int *counter_ptr;
};

void *Producer(void* args){
    struct Args *data = (struct Args*) args;
    //change counter value here which should be changed in main too
    *(data->counter_ptr)++;
}

int main(){
    ...
    ...

    int counter = 0; //will be updated in Producer function
    struct Args args;
    args.counter_ptr = &counter;
    args.name = "";
    pthread_create(&thread_id, NULL, Producer, &args);
    // You need to join thread here to prevent program termination.
    return 0;
}

但总的来说,我认为这里没有任何理由。