Reputation: 385
How do I pass a struct through the pthread_create to my function? The errors I keep getting are that lower and upper has not been defined which would lead me to believe that the struct was not passed properly. I have tried referencing lower as arg1.lower and my error back is saying im trying to request for the member of a non class type void*
void * mergeSortThread(void *arg1){
std::ostringstream ostr;
ostr << "begin: " << lower << " " << upper << endl;
string message = ostr.str();
write(2, message.data(), message.length());
}
int main(int argc, char** argv)
{
struct MergeSortThreadArg
{
int * array;
int * temp;
int lower, upper;
};
pthread_attr_t attr;
pthread_attr_init(&attr);
int arr[20];
int temp[20];
MergeSortThreadArg arg;
arg.array = arr;
arg.temp = temp;
arg.lower = 0;
arg.upper = 19;
pthread_create(th, &attr, mergeSortThread, &arg);
pthread_join(th[z], NULL);
return 0;
}
Upvotes: 0
Views: 204
Reputation: 11007
Define struct before mergeSortThread() and add casting of arg1 to struct MergeSortThreadArg * it in mergeSortThread():
void * mergeSortThread(void *arg1){
struct MergeSortThreadArg *p_MST = (struct MergeSortThreadArg *)arg1;
std::ostringstream ostr;
ostr << "begin: " << p_MST->lower << " " << p_MST->upper << endl;
...
Moreover, it's more correct/safe to allocate the struct and its fields (array and tmp) to avoid passing to new thread data located on stack of another thread.
Upvotes: 1