在pthread中传递结构

时间:2014-12-06 00:06:25

标签: c parallel-processing pthreads

我正在尝试在创建线程时传递结构,但似乎无法正常工作!

这是结构:

struct analyse_data {
    int verbose; //should be 1 or 0
};

请注意,详细信息只能是1或0而不是其他内容。

这是被调用的方法(注意它可以通过另一种方法多次调用):

void dispatch(struct pcap_pkthdr *header, const unsigned char *packet,
        int verbose) {

    static bool thread_settings_initialised = false;

    printf("Verbose: %d\n", verbose); //Prints 1 or 0

    //Only run the first time dispatch method runs
    if (thread_settings_initialised == false){
        thread_settings_initialised = true;

        //...    

        //Set mutex for the appropriate variables to remain thread safe
        //...

        //Set attr so threads are "Detached"
        pthread_attr_init(&attr);
        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

        //Set pthread_cond_init
        //...
    }

    //Put parameters into a struct so can be sent in a thread
    struct analyse_data data;
    data.verbose = verbose;

    //...

    pthread_t tid;
    printf("data.verbose: %d\n", data.verbose); //This prints 1 or 0
    int rc = pthread_create( &tid, &attr, bar, (void *) &data);
    if (rc) {
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
    }

}

这是线程调用的方法:

void analyse(void *thread_data) {
    struct analyse_data *data;
    data = (struct analyse_data *) thread_data;
    int verbose = data->verbose;
    printf("Verbose =  %d\n", verbose ); //Prints weird numbers like -547845...
}

从我的评论中可以看出,verbose的值在方法中使用时会发生变化。为什么?我究竟做错了什么?

非常感谢!

更新(感谢JS1) 我更新了我的代码以使用指针:

void dispatch(struct pcap_pkthdr *header, const unsigned char *packet,
        int verbose) {

    static bool thread_settings_initialised = false;

    printf("Verbose: %d\n", verbose); //Prints 1 or 0

    //...

    //Put parameters into a struct so can be sent in a thread
    struct analyse_data *data = malloc(sizeof(struct analyse_data)); //NEW
    data->verbose = verbose;

    //...

    pthread_t tid;
    printf("data.verbose: %d\n", data.verbose); //This prints 1 or 0
    int rc = pthread_create( &tid, &attr, bar, (void *) data);
    //...
}

但是现在analyze()方法总是输出0,即使verbose是1!

1 个答案:

答案 0 :(得分:1)

您不应将堆栈变量传递给pthread_create。请注意data是函数dispatch的本地函数,并且在dispatch返回时将超出范围。您应该使用malloc来分配data,或使用静态或全局变量。

如果您使用malloc方法,它将如下所示:

struct analyse_data *data = malloc(sizeof(struct analyse_data));
data->verbose = verbose;

int rc = pthread_create( &tid, &attr, bar, data);

您必须记住不要从free致电data上的dispatch。记忆应该属于#34;到线程,所以当你完成使用free的内容时,你最终应该从线程data上调用data

相关问题