Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 821
user3001499 Avatar asked Dec 05 '25 08:12

user3001499


2 Answers

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.

like image 190
Wintermute Avatar answered Dec 07 '25 21:12

Wintermute


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;
like image 22
Severin Pappadeux Avatar answered Dec 07 '25 22:12

Severin Pappadeux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!