简体   繁体   中英

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 %d\n", res);
    }

    printf("main thread\n");
    return 0;
}

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.

the behaviour of your code depends on the scheduler; probably the main program exits before printf in the created thread has been executed. I hope simple sleep(some_seconds) at the end of the main() will cause the thread output to appear:)

the join call waits for the thread to terminate and exit.

if you want your main thread to continue its execution while the child thread is executing, don't call join : the child thread will execute concurrently with the main thread...

Just create the thread with the detached attribute set to on. To achieve this, you can either call pthread_detach after the thread has been created or pthread_attr_setdetachstate prior to its creation.

When a thread is detached, the parent thread does not have to wait for it and cannot fetch its return value.

you need to call pthread_exit in the end of man(), which will cause main to wait other thread to start and exit. Or you can explicitly call pthread_join to wait the newly created thread

Otherwise, when main returns, the process is killed and all thread it create will be killed.

The thread starts automatically when you create it.

Don't you just need to call pthread_create ?

static void *thread_body(void *argument) { /* ... */ }

int main(void) {
    pthread_t thread;
    pthread_create(&thread, NULL, thread_body, NULL);
    /* ... */

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