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

M B*_*M B 1 c++ concurrency multithreading posix pthreads

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

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

谷歌(和这里)上的答案通常是对代码中一个特定问题的答案,我不知道如何真正让这件事起作用。

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

我显然做错了什么,我的猜测是第 18 行,但是我没有足够的经验来自己解决这个问题,我正在向你们寻求帮助。

这个结构向函数传递多个参数我做错了什么?

我的实际任务比这要复杂一些,但我已尽力使其尽可能清楚。

caf*_*caf 5

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

struct Data *input;
Run Code Online (Sandbox Code Playgroud)

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

struct Data input;
Run Code Online (Sandbox Code Playgroud)

进而:

input.a = arg;
input.b = arg2;
Run Code Online (Sandbox Code Playgroud)

其余的应该可以正常工作。