POSIX 线程,将多个参数传递给具有结构的函数

POSIX thread, passing multiple arguments to function with a struct

所以我花了最后几个小时试图 google 找出我的代码有什么问题,但我无法弄清楚。

我是一名学生,我刚刚开始学习线程等,所以这对我来说都是全新的,我也不是很有经验。

google(以及此处)上的答案通常是对代码的一个特定问题的答案,我无法弄清楚如何让这个东西真正起作用。

这是我的代码的一个非常简化的版本:

http://pastebin.com/wst8Yw8z

#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

using namespace std;

struct Data{
    string a;
    string b;
};

void* thread_func( void *param ){

    struct Data *input = (struct Data*)param;

    string data1 = input->a;
    string data2 = input->b;

    cout << "You said: " << data1 << " " << data2 << endl;

    return NULL;
}

int main( int argc, char *argv[] )
{
    pthread_t child;
    string arg, arg2;

    struct Data *input;

    cout << "Input 1: " << endl;
    cin >> arg;
    cout << "Input 2: " << endl;
    cin >> arg2;

    input->a = arg;
    input->b = arg2;

    pthread_create( &child, NULL, thread_func, (void *)&input);

    pthread_join( child, NULL );
    cout << "Synced" << endl;
    return 0;
}

所以我有一个数据结构,我想用它来将多个参数传递给函数thread_func。

我的代码实际上编译了(至少在 linux 上)但是当我输入两个值时,我得到了分段错误。

我显然做错了什么,我猜是第 18 行,但是我没有足够的经验自己解决这个问题,我想请你们帮忙。

我将多个参数传递给函数的结构有什么问题?

我的实际任务比这复杂一点,但我尽力让它尽可能清楚。

这一行:

struct Data *input;

将输入定义为指针,但在稍后使用它来存储您的字符串之前,它从不分配对象:

input->a = arg;
input->b = arg2;

根据您对 pthread_create 的调用,我怀疑您根本不希望 input 成为指针。删除 *,并将分配更改为:

input.a = arg;
input.b = arg2;

在你的 main() 函数中,这个:

struct Data *input;

创建指向 struct Data 的指针,但不会创建实际的 struct Data 对象本身。你需要在这里使用:

struct Data input;

然后:

input.a = arg;
input.b = arg2;

其余的应该没问题。