Reputation: 539
I have this piece of code shown below.
Where nrthr stands for number of threads and is entered by the user. I always want my "main program" to call testFunc once, so if the user enter nrthr to be number 3 I then want to create 2 new threads. So my question is... how can I just call testFunc before the while loop?
int threadCount = 0;
...
// Call testFunc here
while(threadCount < nrthr - 1) {
fprintf(stderr, "Created thread: %d\n", threadCount);
if(pthread_create(&(tid[threadCount++]), NULL, testFunc, args) != 0)
fprintf(stderr, "Can't create thread\n");
}
void *testFunc(void *arg)
{
...
}
Upvotes: 0
Views: 105
Reputation: 32261
If testFunc
is supposed to run on a separate thread, then it may be the case that it doesn't simply do something and return.
If that assumption is true, you can't simply call it before your loop, otherwise your main thread won't reach the point of creating the other threads to run simultaneously.
If that assumption is false, then you can simply call it like any other function, testFunc(args)
, and ignore the return value if you don't care about it. Another thing to note is the behaviour of pthread_exit
when it's called from the main thread - See Is it OK to call pthread_exit from main?.
Upvotes: 2
Reputation: 225827
You can call testFunc
like this:
void *result = testFunc(args);
Beware, however, if testFunc
calls any pthread related functions. Since in this case the function is not running in a separate thread, calling functions like pthread_exit
will not work as you might expect.
Upvotes: 2