多参数函数通过在pthread_create()调用? [英] Multiple arguments to function called by pthread_create()?

查看:135
本文介绍了多参数函数通过在pthread_create()调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要多个参数传递给我想一个单独的线程调用一个函数。我阅读,要做到这一点的典型方式是定义一个结构,一个指针传递的功能这一点,解引用它的参数。但是,我无法得到这个工作:

I need to pass multiple arguments to a function that I would like to call on a separate thread. I've read that the typical way to do this is to define a struct, pass the function a pointer to that, and dereference it for the arguments. However, I am unable to get this to work:

#include <stdio.h>
#include <pthread.h>

struct arg_struct {
    int arg1;
    int arg2;
};

void *print_the_arguments(void *arguments)
{
    struct arg_struct *args = (struct arg_struct *)args;
    printf("%d\n", args -> arg1);
    printf("%d\n", args -> arg2);
    pthread_exit(NULL);
    return NULL;
}

int main()
{
    pthread_t some_thread;
    struct arg_struct args;
    args.arg1 = 5;
    args.arg2 = 7;

    if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {
    	printf("Uh-oh!\n");
    	return -1;
    }

    return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}

这个输出应该是:

The output for this should be:

5
7

但是当我运行它,我实际上得到:

But when I run it I actually get:

141921115
-1947974263

任何人都知道我在做什么错了?

Anyone know what I'm doing wrong?

推荐答案

由于你说

结构arg_struct * ARGS =(结构arg_struct *)ARGS;

而不是

结构arg_struct * ARGS =参数;

这篇关于多参数函数通过在pthread_create()调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆