pthread:一个 printf 语句在子线程中打印两次 [英] pthread: one printf statement get printed twice in child thread

查看:69
本文介绍了pthread:一个 printf 语句在子线程中打印两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个 pthread 程序,我不知道为什么 printf 语句在子线程中打印两次:

this is my first pthread program, and I have no idea why the printf statement get printed twice in child thread:

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):

Observed output on my platform (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,子线程的两条输出线

for 3, two output lines from the child thread

对于4,和3一样,连输出都是交错的.

for 4, the same as 3, and even the outputs are interleaved.

推荐答案

看起来真正的答案是 Michael Burr 的评论,它引用了这个 glibc 错误:https://sourceware.org/bugzilla/show_bug.cgi?id=14697

It looks like the real answer is Michael Burr's comment which references this glibc bug: https://sourceware.org/bugzilla/show_bug.cgi?id=14697

总而言之,glibc 在程序退出时没有正确处理 stdio 缓冲区.

In summary, glibc does not handle the stdio buffers correctly during program exit.

这篇关于pthread:一个 printf 语句在子线程中打印两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆