-4

Am new to C, am trying to create thread using below code but i unable to create thread, Can any one tell me where i am going wrong... It is not going into 'if' loop and not calling 'myfunction'

void *myfunction() {
   //my code
}

void createThreadForMyFunction(void) {
   pthread_t thread_ID;
   if(pthread_create(&thread_ID, NULL, myfunction, NULL)) {
         printf("pthread_create");
    }
}
MikeMB
  • 20,029
  • 9
  • 57
  • 102
Nevin
  • 169
  • 1
  • 2
  • 7
  • 2
    [`On success, pthread_create() returns 0`](http://man7.org/linux/man-pages/man3/pthread_create.3.html) – red0ct May 12 '16 at 07:26
  • @red0ct But why function is not getting called.....do i need to call the function explicitly after thread creation.. – Nevin May 12 '16 at 07:29
  • 1
    We can't deduce much else from your question. Please read the help pages on how to create a minimal complete example for the problem and ask a new question. – Jens Gustedt May 12 '16 at 08:10

3 Answers3

2

pthread_create returns 0 on success. So you could add ! to your if statement or do something like:

if (pthread_create...) {
    perror("CREATE");
    return;
} 
/* other code */

To make the main function wait child with id threadID you also may just do pthread_join(threadID, NULL); after thread creation without using sleep and friends.
Read.

Community
  • 1
  • 1
red0ct
  • 4,840
  • 3
  • 17
  • 44
1

Return value of pthread_create is an int that is 0 on success. So if you are not entering in your if function, it is because your thread was successfully created.

So your function myFunction is actually called, in your new thread.

Note that if your main thread (the one executing createThreadForMyFunction) end too quickly, it kills the child thread (the one executing myFunction) before it prints anything, and you won't see if your thread was successfully created. Try to add a usleep after the thread creation in order to give some time to your new thread to show itself.

Aracthor
  • 5,757
  • 6
  • 31
  • 59
0

Try it:

void* myfunction(void *arg)
{
  // do somthing
}

int main(void)
{
   pthread_t thread_ID;
   int err;

        err = pthread_create(&thread_ID, NULL, &myfunction, NULL);
        if (err != 0)
            printf("\ncan't create thread :[%s]", strerror(err));
        else
            printf("\n Thread created successfully\n");
    }

    sleep(5);
    return 0;
}
msc
  • 33,420
  • 29
  • 119
  • 214