【发布时间】: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