【问题标题】:POSIX thread, passing multiple arguments to function with a structPOSIX线程,将多个参数传递给带有结构的函数
【发布时间】:2017-05-25 15:37:46
【问题描述】:

所以我在过去的几个小时里试图用谷歌搜索并找出我的代码出了什么问题,但我无法弄清楚。

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

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

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

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 行,但是我没有足够的经验来自己解决这个问题,我正在向你们寻求帮助。

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

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

【问题讨论】:

    标签: c++ multithreading concurrency pthreads posix


    【解决方案1】:

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

    struct Data *input;
    

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

    struct Data input;
    

    然后:

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

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

    【讨论】:

    • 谢谢,这个解决方案解决了这个问题。感谢帮助。 :)
    【解决方案2】:

    这一行:

    struct Data *input;

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

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

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

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

    【讨论】:

    • 谢谢。这解决了问题。太感谢了。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2013-04-20
    • 1970-01-01
    • 2016-10-05
    • 2022-08-05
    • 1970-01-01
    相关资源
    最近更新 更多