简体   繁体   English

是什么让 Printf 打印两次?

[英]What makes Printf prints twice?

I did everything in my hands and think it's time to ask for help.我做了一切,认为是时候寻求帮助了。

The following snippet of code runs by the main thread Only and my whole code doesn't call fork() at all.以下代码片段仅由主线程运行,我的整个代码根本不调用 fork()。

inside another function:在另一个 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));

For some really strange reason, sometimes I see the same i value being printed twice.由于某些非常奇怪的原因,有时我会看到相同的i值被打印两次。 For example, one output was:例如,一个 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  

How is this even possible?这怎么可能?

Important Note: those are the only printings in my code so that second i can't come from different code...重要说明:这些是我的代码中唯一的印刷品,所以第二个i不能来自不同的代码......

I don't see any great mystery here.我看不出这里有什么大秘密。 You have:你有:

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

So the loop executes twice and therefore prints everything twice.所以循环执行两次,因此将所有内容打印两次。

What is probably confusing you is that you have written:可能让你感到困惑的是你写过:

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

when you probably meant:当您可能的意思是:

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

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

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