简体   繁体   中英

POSIX thread, passing multiple arguments to function with a struct

So I've spent the last few hours trying to google and figure out what is wrong with my code but I couldn't figure out.

I'm a student and I just started learning about threads etc so this is all brand new to me and I'm not very experienced.

Answers on google (and on here) were usually answers to one particular problem with the code and I couldn't figure out how to actually get this thing to work.

Here's a very simplified version of my code:

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;
}

So I have a struct Data that I want to use to pass multiple arguments to the function thread_func.

My code actually compiles (at least on linux) but when I input both values, I get Segmentation fault.

I am clearly doing something wrong and my guess would be the line 18, however I am not experienced enough to figure this out on my own and I'm asking you guys for help.

What am I doing wrong with this struct to pass multiple arguments to the function?

My actual assignment is a bit more complicated than this but I did my best to make it as clear as possible.

In your main() function, this:

struct Data *input;

creates a pointer to a struct Data , but doesn't create an actual struct Data object itself. You need to use here:

struct Data input;

and then:

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

and the rest should work fine.

This line:

struct Data *input;

Defines input as a pointer, but it never allocates the object before later using it to store your strings here:

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

Based on your call to pthread_create I suspect you do not want input to be a pointer at all. Remove the * , and change the assignments to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM