C pthread_creat() 输出重复的数字

C pthread_creat() output repeated numbers

C代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void *helloFunc(void *ptr)
{
    int *data;
    data = (int *)ptr;
    printf("I am thread %d\n", *data);
}
int main(int argc, char *argv[])
{
    pthread_t hThread[4];
    for (int i = 0; i < 4; i++)
        pthread_create(&hThread[i], NULL, helloFunc, (void *)&i);
    for (int j = 0; j < 4; j++)
        pthread_join(hThread[j], NULL);
}

我运行在Ubuntu20.04上的代码,发现输出是这样的

I am thread 2
I am thread 4
I am thread 4
I am thread 3
I am thread 1
I am thread 3
I am thread 4
I am thread 2
I am thread 3
I am thread 4
I am thread 4
I am thread 4

我想知道为什么输出有一些重复的数字而不是 1、2、3、4 的随机列表

您将 i 的地址传递给每个线程。当线程取消引用它来读取它时,它可能在主线程中增加了 0 次或更多次,因此您在线程中读取的内容是不确定的。

您可以创建一个 int[4] 数组并将每个单独的 int 的唯一地址传递给启动的线程 - 或者您可以将 pthread_t 及其数据打包在一个 struct 将连接到某个线程的所有内容存储在一个地方。

示例:

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

typedef struct {
    pthread_t th;
    int i;
    /* add more data fields to the struct if needed */
} threadinfo;

void *helloFunc(void *ptr)
{
    threadinfo* ti = (threadinfo*) ptr;
    printf("I am thread %d\n", ti->i);
}

int main(void)
{
    threadinfo hThread[4];
    for (int i = 0; i < 4; i++) {
        hThread[i].i = i;         /* fill in the data fields */

        /* and pass the address of the threadinfo struct as a parameter here */
        pthread_create(&hThread[i].th, NULL, helloFunc, (void *)&hThread[i]);
    }
    for (int j = 0; j < 4; j++)
        pthread_join(hThread[j].th, NULL);
}