Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code not run?

void myThread(void *arg) {
    printf("Thread ran!\n");
    pthread_exit( NULL );
}

int main() {
    int ret;
    pthread_t mythread;
    ret=pthread_create(&mythread,NULL,myThread,NULL);
    if (ret != 0) {
            printf( "Can’t create pthread (%s)\n", strerror(errno ) );
            exit(-1);
    }
    return 0;
}
like image 227
Davood Hanifi Avatar asked Feb 15 '26 13:02

Davood Hanifi


1 Answers

Because main returns immediately, before the thread has had a chance to execute - try adding sleep(1000); before return 0; and you'll probably find that it works.

If you'd like main to wait until the thread finishes, try pthread_join (but then you might as well not have a thread at all).

pthread_join(mythread, 0);
return 0;
like image 107
James McLaughlin Avatar answered Feb 19 '26 10:02

James McLaughlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!