c - 从线程打印时值不一致

标签 c multithreading

我正在学习线程编程,并且一直在运行测试练习,以了解当您从 pthread_create 调用函数时它是如何工作的,但是,我在执行此操作时得到了奇怪的结果。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

pthread_t *threads;

typedef struct _file {
    int num1;
    int num2;
} file;

void thread_run(void *thing) {
    file *fp = thing;

    printf("num1: %d num2: %d\n", fp->num1, fp->num2);

}

int main(int argc, char **argv) {

    threads = (pthread_t *)malloc(atoi(argv[1]));

    file *args = malloc(sizeof(file));
    args->num1 = 0;
    args->num2 = 0;
    int i;
    for (i = 0; i < atoi(argv[1]); i++) {
        args->num1 = i;
        args->num2 = i + 1;
        pthread_create(&threads[i], NULL, (void *)thread_run, (void *)&args); // the (void *) cast is necessary on my linux distro
    }

    for (i = 0; i < atoi(argv[1]); i++) {
        pthread_join(threads[i], NULL);
    }

    return 0;
}

我在这里尝试的是,当我在 for 循环中创建线程时,我将它们全部存储在我的 *threads 指针中。

然后我使用一个结构参数调用 thread_run 方法,该参数包含我要打印的两个整数值。

据我所知,使用 ./a.out 3 运行该程序时的预期输出应该是:

num1: 0 num2: 1
num1: 1 num2: 2
num1: 2 num2: 3

但是,我得到的输出每次都会有所不同,但通常与以下内容一致:

num1: 34185264 num2: 0
num1: 34185264 num2: 0
num1: 34185264 num2: 0

我注意到一些具有类似主题的问题,但其他用户似乎都没有遇到我所描述的问题。

最佳答案

每个线程都有一个指向完全相同的结构的指针。因此,它们将打印相同的值。您应该为 for 循环内的每个线程 malloc() 一个新的结构。

此外,args 被声明为 file *args。请注意,这已经是一个指针,因此您应该直接传递它而不是它的地址:

pthread_create(&threads[i], NULL, (void *)thread_run, (void *)args);

关于c - 从线程打印时值不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40601587/

相关文章:

c语法: array

c++ - 将不可复制的类型转发到 std::thread

c++ - 套接字窗口异常。读取访问冲突

c - 如何使用 libxml2 解析 XML 中的数据?

c++ - Arduino清除缓冲区

c - C 中的结构数组参数

c# - 一个 C# 异常可以在不同线程上多次引发吗?

c - C语言中的简单字符解释

java - 互斥使用JAVA 2-Threads解决方案

.net - 限制程序集执行的 cpu 周期数