开发者

Problem while compiling pthreads program

I tried to compile this simple pthreads program with this command

$ gcc -pthread -o pthreads pthreads.c
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h&g开发者_如何学Got;
#include <string.h>
#include <errno.h>

void *myThread(void *arg);

int main()
{
    pthread_t mythread;
    int ret;

    ret = pthread_create( &mythread, NULL, myThread, NULL );

    if (ret != 0){
        printf( "Can't create pthread: %s", strerror(errno));
        exit(-1);
    }
    return 0;
}

void *myThread(void *arg){

    // Thread code goes here..
    printf("OK! NOW ON THE THREAD\n");
    pthread_exit(NULL);
}

but when trying ./pthreads there is no output presented!!


You need to wait for the thread to finish. Otherwise you risk exiting before the thread starts executing.

... 
pthread_create( &mythread, NULL, myThread, NULL );
...
// Wait for the thread to finish.
pthread_join( mythread, NULL);


You didn't wait for your thread to finish. You need to use pthread_join().


You problem comes from the fact that you're main thread is returning from main, and thus calling exit (or _exit). All running thread are killed when the program exit. In this case, the worker thread didn't have the time to execute before it is killed.

You can use pthread_join to wait for the completion of the thread before returning from main.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

void *myThread(void *arg);

int main()
{
    void* thread_return;
    pthread_t mythread;
    int ret;

    ret = pthread_create(&mythread, NULL, myThread, NULL);
    if (ret != 0)
    {
        printf("Can't create pthread: %s\n", strerror(errno));
        exit(-1);
    }

    ret = pthread_join(mythread, &thread_return);
    if (ret != 0)
    {
        printf("Can't join pthread: %s\n", strerror(errno));
        exit(-1);
    }

    return 0;
}

void *myThread(void *arg)
{
    printf("OK! NOW ON THE THREAD\n");
    pthread_exit(NULL);
}


Sanjit's answer is certainly correct, but for the sake of enlarging your threads toolbox, you might also look at pthread_barrier_wait. When you have a simple program with a lot of threads and main looks like "start all worker threads and wait for them to finish", having main and all the workers simply wait on a barrier can be a nice way to avoid having to store all the worker thread ids and join them in a for loop. Barriers also have a lot of other neat uses that sometimes let you avoid unnecessary complexity from doing the same things with mutexes and condition variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜