不同线程的相同线程 ID 的问题

Problem with same thread ID for different threads

我的线程有问题。我正在尝试创建 10 个线程,并且我想为每个线程打印线程 ID。我能够打印线程 ID,但问题是所有线程都打印出相同的线程 ID。

这是我的代码:

主要内容:

int main(void)
{
    int check_error;
    pthread_t clientThread[10];
    
    printf("creating a client thread..!\n");
    fflush(stdout);
    
    for(int i=0; i<10;i++){
        check_error=pthread_create(&clientThread[i], NULL, mqClient, NULL);

        if(check_error!=0)
            printf("Error when creating thread: %s", strerror(check_error));
        else
            pthread_join(clientThread[i], NULL);
    }

    return EXIT_SUCCESS;
}

mqClient:

void * mqClient(void * arg){
    pthread_mutex_lock(&mutex);

    mqd_t mq_on_server;
    struct pt planet;

    char thread_id[30];
    sprintf(thread_id, "%d", pthread_self());

    usleep(1000);

    int response = MQconnect(&mq_on_server, "/servermq");

    if(response==0){
        printf("Something went wrong with MQconnect\n");
    }
    else{

        printf("\nEnter planet name: ");
        scanf("%s", planet.name);

        printf("\nEnter planet X-position: ");
        scanf("%lf", &planet.sx);

        printf("\nEnter planet Y-position: ");
        scanf("%lf", &planet.sy);

        printf("\nEnter planet X-velocity: ");
        scanf("%lf", &planet.vx);

        printf("\nEnter planet Y-velocity: ");
        scanf("%lf", &planet.vy);

        printf("\nEnter planet mass: ");
        scanf("%lf", &planet.mass);

        printf("\nEnter planet life time: ");
        scanf("%d", &planet.life);

        strcpy(planet.pid, thread_id);

        printf("id: %s", planet.pid);

        printf("\n---------------------------------------");
    }


    MQwrite (mq_on_server, &planet);

    int c;
    while ( (c = getchar()) != '\n' && c != EOF);

    pthread_mutex_unlock(&mutex);

    return NULL;
}

测试两个线程时,这是输出(观察相同的线程 ID):

Planet name: dsadas
Planet X-position: 321.000000
Planet Y-position: 321.000000
Planet X-velocity: 321.000000
Planet Y-velocity: 312.000000
Planet mass: 321.000000
Planet life time: 321
Planet thread ID: 1058301696
---------------------------------------
Planet name: ytyr
Planet X-position: 3123.000000
Planet Y-position: 54.000000
Planet X-velocity: 56.000000
Planet Y-velocity: 231.000000
Planet mass: 546.000000
Planet life time: 231
Planet thread ID: 1058301696

每个线程的线程 ID 应该是唯一的,所以知道为什么我会得到这种输出吗?

main 的循环中,您创建了 10 个线程,但您没有并行创建它们。您一次创建一个线程,等待它结束,然后才继续循环。所以你一次只创建0-1个线程,而不是0-10个线程。

一般情况下:同时存在的两个线程有​​不同的ID,但是在不同时间点存在的两个线程可以有相同的ID。