簡體   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