C ++: pass structure to PThread
So I am trying to pass multiple values ββto a stream 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 lost any code (including #include
thrad join, etc.). I find it unnecessary for this question for the sake of simplicity, however, if more code is required, just ask.
The thread worked fine when passing only one integer variable.
This is the error I am getting:
In the function 'void * Process_Data (void *): error: request for the member' test_variable 'in' data_struct ', which is of the non-class type' void * 'testing.test_variable = * ((int *) data_test. Test_variable);
And the same for another variable
Thanks in advance for any advice.
source to share
The usual way
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 are getting the error you received because you are trying to select members from an index void
that does not exist. To use a structure that you know a pointer is pointing to void
, you must cast it back to a pointer to that structure.
Also note that you must have the pthread_join
thread you just started, or main will end before it can do anything.
source to share