这是我的第一个 pthread 程序,我不知道为什么 printf 语句会在子线程中打印两次:
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);
}
在我的平台上观察到的输出(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
对于 3,来自子线程的两条输出线
对于 4,与 3 相同,甚至输出也是交错的。