线程调用堆栈中的变量意外更改 c

variable in thread callstack changing unexpectedly c

使用 c11 线程,我试图确保 foo 是线程安全的。虽然 foo 不可重入,但我正在尝试使用互斥体来缓解这种情况。

我不明白为什么 thrdn 的值在关键循环中发生变化。我的理解是,每个对 foo 的线程调用都会有自己的 thrdn 版本,但它似乎在 运行 时间被其他线程修改。

我试过将 mtx_lock 移动到 thrdn 的声明上方,并将 thrdn 更改为 atomic_int * 类型,但是这两者都会导致相同的行为。

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

#define THREAD_MAX 5

thrd_t threads[THREAD_MAX];
mtx_t mtx;

void foo(void * data)
{
        int* thrdn = (int *)data;

        mtx_lock(&mtx);
        for(int i = 0; i < 3; ++i) {
                printf("thread %d, number %d\n", *thrdn, i);
        }
        mtx_unlock(&mtx);
}

int main()
{
        mtx_init(&mtx, mtx_plain | mtx_recursive);
        for(int i = 0; i < THREAD_MAX; ++i){
                thrd_create(&threads[i], foo, &i);
        }

        for(int i = 0; i < THREAD_MAX; ++i){
                thrd_join(threads[i], NULL);
        }
        mtx_destroy(&mtx);
}

如评论中所述,问题是对局部变量 i 的引用。如 答案中所示单独跟踪线程 ID 解决了该问题。