【发布时间】:2018-05-10 18:37:19
【问题描述】:
我在通过 pthread_create 作为参数传递数组元素时遇到了一些问题。
我有这个结构:
struct threadInfo {
int threadNumber;
int sleepTime;
};
我像这样初始化数组(在函数中):
struct threadInfo info[1];
然后在一个while循环中我这样做:
int i = 0;
...
while (i < 2) {
pthread_mutex_lock(&countMutex);
if (threadsCount < MAX_THREAD) {
info[i].threadNumber = ++threadsCount;
pthread_mutex_unlock(&countMutex);
info[i].sleepTime = rand() % (10 + 1 - 1) + 1;
pthread_create(&threads[i], NULL, lawine, &info[i]);
i++;
}
else {
pthread_mutex_unlock(&countMutex);
break;
}
}
threadsCount 是一个全局变量。
在第一回合它工作正常(信息[0])。但在第二轮 (info1) 中,值是错误的。 the output
你能帮帮我吗?
【问题讨论】:
-
请不要将输出作为链接发布,也不要发布文字图片而是发布文字。
-
你如何像这样初始化数组(在函数中):
struct threadInfo info[];? -
遇到错误时,从代码中删除不重要的部分总是有帮助的,直到您拥有"Short, Self Contained, Correct (Compilable), Example",这样您就可以 (a) 更清楚地看到和理解发生了什么错误 (b) 能够与他人共享一个程序,他们可以轻松地保存为文件、编译并在尝试帮助您时自己尝试。
-
这就是为什么我们不应该在源代码中使用“幻数”。
-
非常有帮助的先生