c - pthread_create() 调用的函数有多个参数?

标签 c pthreads

我需要将多个参数传递给一个我想在单独线程上调用的函数。我有 read做到这一点的典型方法是定义一个结构,向函数传递一个指向它的指针,然后为参数取消引用它。但是,我无法让它工作:

#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 */
}

这个的输出应该是:

5
7

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

141921115
-1947974263

有人知道我做错了什么吗?

最佳答案

因为你说

struct arg_struct *args = (struct arg_struct *)args;

代替

struct arg_struct *args = arguments;

关于c - pthread_create() 调用的函数有多个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1352749/

相关文章:

Linux内核与用户空间程序的通信

c - 如何在unix机器上创建c exe

c - 客户端/服务器中的 write()/read(),C 中的 pthread 应用程序在非主线程上总是返回 -1?

C/unix 套接字 : Segmentation fault (core dumbed) due to char pointer(? )

objective-c - block 作为 C 函数的参数或返回值

c - 功能参数差异

c++ - 为什么 isalpha() 的返回类型是 int 而不是 bool?

c++ - std::thread vs pthread,我做错了什么?

c++ - 如何唤醒休眠的 pthread?

c++ - 并行 Dijkstra 死锁