Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pthread_create question

Status
Not open for further replies.

ragnarocc

Programmer
Mar 9, 2009
3
US
Hey, kinda feels like I'm in over my head here, but trying to learn how to use pthread_create and am having problems with passing in arguments. Right now, I have

a = pthread_create(&thread1, NULL, MatrixTimes, (Matrixa, 0, i, MAX, Matrixb));

in my code calling pthread create, and

void MatrixTimes(int Matrixa[5][5], int start, int end, int max, int Matrixb[5][5])

as my function prototype. What I can gather from reading and the internet is that I need to create a void pointer and pass my arguements in that way... and that's where I go over my head. I see how it works with one item passed in, but looking to pass in several, 5 to be exact. Any help, or directions to a good pthread tutorial, would be much appreciated. Thanks.
 
If you've got multiple arguments, then you need to put them into a struct, then pass a pointer to an instance of that struct.

Code:
struct matArgs {
    int Matrixa[5][5];
    int start;
    int end;
    int max;
    int Matrixb[5][5];
};

Which would be used as
Code:
struct matArgs args;
// fill in args
a = pthread_create(&thread1, NULL, MatrixTimesWrapper, &args);

Where MatrixTimesWrapper is something like
Code:
void *MatrixTimesWrapper ( void *p ) {
    struct matArgs *m = p;
    MatrixTimes(m->Matrixa, m->start, m->end, m->max, m->Matrixb);
    return NULL;
}

If you're intending to use the same function over and over, in different threads, with different arguments, then it's a really good idea to use [tt]malloc()[/tt] to allocate each thread-specific instance of matArgs where the threads are created, and call [tt]free()[/tt] inside the thread when it has finished looking at the parameters.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top