【问题标题】:What makes Printf prints twice?是什么让 Printf 打印两次?
【发布时间】:2021-08-21 00:40:39
【问题描述】:

我已经做好了一切,认为是时候寻求帮助了。

以下 sn-p 代码仅由主线程运行,我的整个代码根本不调用 fork()。

在另一个函数内部:

pthread_mutex_lock(&(q->m));
...
else if (q->schedule_algorithm == RandomDrop)
        {
            int to_drop = 2;
            fprintf(stderr, "Before queue size: %d  \n", q->queue_size);
            fprintf(stderr, "To drop: %d  \n", to_drop);
            while (to_drop > 0)
            {
                // print process id to make sure it's same process
                fprintf(stderr, "process id: %d  \n", getpid());

                // print pthread id to make sure it's same thread
                fprintf(stderr, "\n");
                fprintPt(stderr,pthread_self());
                fprintf(stderr, "\n");
                
                int i = 0;
                int index = my_rand(q->queue_size);
                fprintf(stderr, "rand() chose: %d  \n", index);
                fprintf(stderr, "i: %d  \n", index);
                fprintf(stderr, "____________________\n");
                int removed_fd = find_key(q, index);
                requeue_not_thread_safe(q, removed_fd);
                Close(removed_fd);
                --to_drop;
                ++i;
            }
            fprintf(stderr, "After queue size: %d  \n", q->queue_size);
        }
...
pthread_mutex_unlock(&(q->m));

由于某些非常奇怪的原因,有时我看到相同的i 值被打印了两次。 例如,一个输出是:

Before queue size: 5  
To drop: 2  
process id: 75300  

0x000e3f0a01000000
rand() chose: 2  
i: 2  
____________________
process id: 75300  

0x000e3f0a01000000
rand() chose: 2  
i: 2  
____________________
After queue size: 3  

这怎么可能?

重要提示:这些是我的代码中唯一的打印,因此第二个 i 不能来自不同的代码...

【问题讨论】:

  • 如果你显示 minimal reproducible example 我敢打赌有人会很快发现错误。
  • @TedLyngmo 那是我的程序由服务器和客户端组成的问题,拆分太难了。如果有人感兴趣,调用它的代码由 200 行带有注释的简单行组成。我们可能会弄清楚并编辑这篇文章以显示根本原因
  • 提取所涉及的部分通常不是问题 - 或者从头开始重写以重现它 - 但我看到 Paul 可能已经想通了,所以我赞成这个答案。
  • 让代码更简单
  • @TedLyngmo 是并接受了:)

标签: c multithreading loops printf pthreads


【解决方案1】:

我看不出这里有什么大秘密。你有:

to_drop = 2; (effectively)
while (to_drop > 0)
{
    ...
    --to_drop;
    ++i;
}

因此循环执行了两次,因此将所有内容打印两次。

可能让你感到困惑的是你写的:

fprintf(stderr, "i: %d  \n", index);

当你的意思可能是:

fprintf(stderr, "i: %d  \n", i);

【讨论】:

  • 可能,是的,它确实对事物本身毫无用处。
  • 我的问题值得保留吗?它会帮助某人吗?
  • 这样说吧,我见过更糟的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 2022-11-21
相关资源
最近更新 更多