0
#include <pthread.h>
#include <cstdio>

void *printa(void *) {
    printf("a");
    return NULL;
}

void *printb(void *) {
    printf("b");
    return NULL;
}

int main() {
    pthread_t pa, pb;
    pthread_create(&pa, NULL, printa, NULL);
    pthread_create(&pb, NULL, printb, NULL);
    for(;;);
}

I expect it to print "a" and "b" in any order, but it can run and exit without print anything. Why? ADD: So the reason is the main function exit before the threads was run. So I add a for(;;); in the end of main, and it seems that "a" and "b" is never printed.

lucky yang
  • 1,609
  • 2
  • 13
  • 20

2 Answers2

2

Your program exits before threads are done processing, you need to wait for each thread to finish with pthread_join

Pras
  • 4,047
  • 10
  • 20
1

printf (actually stdout) is generally line buffered. See printf(3) and setvbuf(3) and stdio(3). So the "a" and "b" strings stay in the internal buffer of stdout and you don't observe any output ...

Either add a \n in your printf, or call fflush(3) (perhaps as fflush(NULL); ....) in both printa and printb. See also flockfile(3).

And you should call pthread_join(3) on both pa and pb in your main after the calls to pthread_create, or else have detached threads e.g. with pthread_detach(3). See also this.

Read some good Pthread tutorial. See also pthreads(7).

BTW, the busy loop for(;;); is bad taste (and not environment-friendly: you are wasting power uselessly). Prefer some idle loop, perhaps using sleep(3), nanosleep(2), pause(2), etc; or some event loop (around poll(2), etc...).Of course a call to pthread_join will wait for the thread to terminate.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547