简体   繁体   中英

How do I call a function that returns a void pointer?

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)
{
    ...
}

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.

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? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM