繁体   English   中英

是什么让 Printf 打印两次?

[英]What makes Printf prints twice?

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

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

在另一个 function 里面:

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值被打印两次。 例如,一个 output 是:

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不能来自不同的代码......

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

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

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

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

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

当您可能的意思是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM