Skip to content
Advertisement

pthread – How to start running a new thread without calling join?

I want to start a new thread from the main thread. I can’t use join since I don’t want to wait for the thread to exit and than resume execution.
Basically what I need is something like pthread_start(…), can’t find it though.

Edit:
As all of the answers suggested create_thread should start thread the problem is that in the simple code below it doesn’t work. The output of the program below is “main thread”. It seems like the sub thread never executed. Any idea where I’m wrong?
compiled and run on Fedora 14 GCC version 4.5.1

void *thread_proc(void* x)
{
   printf ("sub thread.n");
   pthread_exit(NULL);
}


int main()
{
    pthread_t t1;
    int res = pthread_create(&t1, NULL, thread_proc, NULL);
    if (res)
    {
        printf ("error %dn", res);
    }

    printf("main threadn");
    return 0;
}

Advertisement

Answer

The function to start the thread is pthread_create, not pthread_join. You only use pthread_join when you are ready to wait, and resynchronize, and if you detach the thread, there’s no need to use it at all. You can also join from a different thread.

Before exiting (either by calling exit or by returning from main), you have to ensure that no other thread is running. One way (but not the only) to do this is by joining with all of the threads you’ve created.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement