【问题标题】:Passing an element of an array (struct) through pthread_create通过 pthread_create 传递数组(结构)的元素
【发布时间】: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) 能够与他人共享一个程序,他们可以轻松地保存为文件、编译并在尝试帮助您时自己尝试。
  • 这就是为什么我们不应该在源代码中使用“幻数”。
  • 非常有帮助的先生

标签: c arrays struct pthreads


【解决方案1】:

您的数组超出了界限,因为您只声明它包含一个元素,但您希望它包含 2。这行代码中方括号内的数字...

struct threadInfo info[1];

... 不是您可以访问的最高索引。它是元素的数量,所以如果你想拥有 2 个元素(从而能够访问 info[1]),你需要像这样分配它:

struct threadInfo info[2];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2023-03-15
    • 2013-11-05
    • 1970-01-01
    • 2013-11-15
    相关资源
    最近更新 更多