0
votes

This is my code, I compiled it with:

gcc thread.c -lpthread

It didn't print any error or warning. But when I run it, the program doesn't print anything.

Platform: Ubuntu 11.10 64 bit gcc 4.6.1
Exit status :0

When I debug it, I found it prints hello as I expected.

This is my code:

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

void *loopPrint(void *ptr)
{
    char *p = (char *)ptr;
    while (1)
    {
        printf("%s\n", p);
    }
}

void *pClock(void *ptr)
{
    sleep(3);
    exit(0);
}

int main()
{
    pthread_t showMsg, clock;
    int main_pth, wait_pth;
    char *msg = "Hello";
    main_pth = pthread_create(&showMsg, NULL, loopPrint, (void *)msg);
    wait_pth = pthread_create(&clock, NULL, pClock, NULL);

    pthread_join(main_pth, NULL);
    pthread_join(wait_pth, NULL);
    return 0;
}
2

2 Answers

4
votes
pthread_join(main_pth, NULL);

This is wrong, pthread_join takes a pthread_t as an argument. Replace with:

pthread_join(showMsg, NULL);

(Same for the other one.)

And do check the return values of these calls, they can and do fail.
And BTW, you're missing #include <unistd.h> for the sleep call.

2
votes

main_pth etc is the error return of pthread_create and not the thread id. Wait ("join") for showMsg and clock.