是什么让 Printf 打印两次?
What makes Printf prints twice?
手上的事都做了,觉得是时候求助了。
以下代码片段仅由主线程运行,我的整个代码根本不调用 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
不能来自不同的代码...
我看不出这里有什么大秘密。你有:
to_drop = 2; (effectively)
while (to_drop > 0)
{
...
--to_drop;
++i;
}
因此循环执行了两次,因此将所有内容都打印了两次。
您可能感到困惑的是您写了:
fprintf(stderr, "i: %d \n", index);
当你的意思可能是:
fprintf(stderr, "i: %d \n", i);
手上的事都做了,觉得是时候求助了。
以下代码片段仅由主线程运行,我的整个代码根本不调用 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
不能来自不同的代码...
我看不出这里有什么大秘密。你有:
to_drop = 2; (effectively)
while (to_drop > 0)
{
...
--to_drop;
++i;
}
因此循环执行了两次,因此将所有内容都打印了两次。
您可能感到困惑的是您写了:
fprintf(stderr, "i: %d \n", index);
当你的意思可能是:
fprintf(stderr, "i: %d \n", i);