pthread: Eine printf-Anweisung wird zweimal im untergeordneten Thread gedruckt

Dies ist mein erstes pthread-Programm, und ich habe keine Ahnung, warum die printf-Anweisung zweimal im untergeordneten Thread gedruckt wird:

int x = 1;

void *func(void *p)
{
    x = x + 1;
    printf("tid %ld: x is %d\n", pthread_self(), x);
    return NULL;
}

int main(void)
{
    pthread_t tid;
    pthread_create(&tid, NULL, func, NULL);

    printf("main thread: %ld\n", pthread_self());

    func(NULL);
}

Beobachtete Ausgabe auf meiner Plattform (Linux 3.2.0-32-generic # 51-Ubuntu SMP x86_64 GNU / Linux):

1.
main thread: 140144423188224
tid 140144423188224: x is 2

2.
main thread: 140144423188224
tid 140144423188224: x is 3

3.
main thread: 139716926285568
tid 139716926285568: x is 2
tid 139716918028032: x is 3
tid 139716918028032: x is 3

4.
main thread: 139923881056000
tid 139923881056000: x is 3
tid 139923872798464tid 139923872798464: x is 2

für 3 zwei Ausgabezeilen vom untergeordneten Thread

Für 4 ist es dasselbe wie für 3, und sogar die Ausgänge sind verschachtelt.

Antworten auf die Frage(3)

Ihre Antwort auf die Frage