user3001499
user3001499

Reputation: 811

C++: Pass struct to PThread

So I am trying to pass several values to a thread by using a struct.

This is what I have:

int main()
{

struct Data
{
int test_data;
int test_again;
};

Data data_struct;
data_struct.test_data = 0;
data_struct.test_again = 1;

pthread_create(&thread, NULL, Process_Data, (void *)&data_struct);
return 0;
}


void* Process_Data(void *data_struct)
{
 struct test
{
    int test_variable;
    int test_two;
};
test testing;
testing.test_variable = *((int *)data_struct.test_data);
testing.test_two = *((int *)data_struct.test_again);
}

I have left out any code (inluding #includes and thrad joins etc) I think is unnecessary for this question for the sake of simplicity, however if more code is needed please just ask.

The thread worked fine when passing just one integer variable.

This is the error I am getting:

In function 'void* Process_Data(void*): error: request for member 'test_variable' in 'data_struct' which is of a non-class type 'void*' testing.test_variable = *((int *)data_test.test_variable);

And the same for the other variable

Thanks in advance for any advice.

Upvotes: 3

Views: 3486

Answers (2)

Severin Pappadeux
Severin Pappadeux

Reputation: 20130

You have untyped void* pointer from which you're trying to extract data

Try first to cast pointer to something and then use it

Data* p = (Data*)data_struct;

int a = p->test_data;
int b = p->test_again;

Upvotes: 1

Wintermute
Wintermute

Reputation: 44073

The usual way is

void* Process_Data(void *data_struct)
{
  Data *testing = static_cast<Data*>(data_struct);

  // testing->test_data and testing->test_again are
  // data_struct.test_data and data_struct.test_again from main
}

You get the error you get because you try to pick members from a void pointer, which does not have any. In order to use the struct you know the void pointer points to, you have to cast it back to a pointer to that struct.

Also, note that you should pthread_join the thread you just started, or main will end before it can do anything.

Upvotes: 4

Related Questions