【问题标题】:Duplicated printf output with two pthreads [duplicate]具有两个 pthread 的重复 printf 输出 [重复]
【发布时间】:2019-03-30 14:29:30
【问题描述】:

我正在学习 pthread。我发现如果我反复运行程序,下面代码的输出可能会很奇怪。 我以这样的方式编写线程1“等待”线程2,主线程“等待”线程1。这种方式是不正确的,因为当 thead1 开始运行时,线程 2 可能不可用,但我仍然想知道为什么线程 2 中的 printf 会被复制。谢谢!

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

pthread_t thread1;
pthread_t thread2;

void* thread1_entry(void* input)
{
    int ret;
    /* This may return error when thread2 has not been created yet*/
    ret = pthread_join(thread2, NULL);
    printf("hello from 1-%d-%s\n", ret, strerror(ret));
    return 0;
}

void* thread2_entry(void* input)
{

    printf("hello from 2\n");

    printf("exit from 2.....\n");

    return 0;
}


int main(void)
{
    int ret1, ret2;

    ret1 = pthread_create(&thread1, NULL, thread1_entry, NULL);

    ret2 = pthread_create(&thread2, NULL, thread2_entry, NULL);

    if (ret1 || ret2)
    {
        printf("error-%d-%d\n", ret1,ret2);
    }
    else
    {
        pthread_join(thread1, NULL); 
    }

    return 0;
}

输出可能不一致(由于调度?),最奇怪的是线程 2 中的 printf 可能重复。

$ ./a.out 
hello from 2
exit from 2.....
hello from 1-0-Success
$ ./a.out 
hello from 1-0-Success
hello from 2
exit from 2.....
exit from 2.....

GCC 版本:

$ gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

【问题讨论】:

    标签: c pthreads


    【解决方案1】:

    不是很漂亮,但你可以有一个全局布尔值来告诉你第二个线程是否写了东西。 所以,

    void* thread1_entry(void* input)
    {   
        while (!second_ended){}
        int ret;
        /* This may return error when thread2 has not been created yet*/
        ret = pthread_join(thread2, NULL);
        printf("hello from 1-%d-%s\n", ret, strerror(ret));
        return 0;
    }
    
    void* thread2_entry(void* input)
    {
    
        printf("hello from 2\n");
    
        printf("exit from 2.....\n");
    
        second_ended = true;
        return 0;
    }
    

    至于为什么会发生,线程是如何工作的 - 真的不可能知道哪个会先启动。

    【讨论】:

    • 是的,我知道在这种情况下 thread1 或 thread2 get to run 是未定义的。我很想知道如果我重复运行程序,为什么 thread2 中的第二个 printf 可能会被调用两次。
    • 我将问题从“不一致”改为“重复”。
    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2021-02-09
    • 2016-01-05
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多