c - 多个线程如何拥有相同的线程ID?

标签 c multithreading ubuntu unix process

我有一个问题:多个线程可以有相同的thread_id吗? (当然不是。)但是我的代码是这样做的。这怎么可能?

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<sys/types.h>

void* message(void* var){
    int t = (int)var;


    printf("\n%d- Hi I'm thread ID=%lu\n",t+1,(int unsigned long)pthread_self());
}

int main(void){
    pthread_t threads[10];
    int report[10];
    for(int i=0;i<10;i++){
        report[i] = pthread_create(&threads[i],NULL,message,(void*)i);
        pthread_join(threads[i],NULL);
    }
    return 0;
}

我在(Ubuntu 17.04)的代码显示了这个结果

1- Hi I'm thread ID=3076250432

2- Hi I'm thread ID=3076250432

3- Hi I'm thread ID=3076250432

4- Hi I'm thread ID=3076250432

5- Hi I'm thread ID=3076250432

6- Hi I'm thread ID=3076250432

7- Hi I'm thread ID=3076250432

8- Hi I'm thread ID=3076250432

9- Hi I'm thread ID=3076250432

10- Hi I'm thread ID=3076250432

最佳答案

for(int i=0;i<10;i++){
    report[i] = pthread_create(&threads[i],NULL,message,(void*)i);
    pthread_join(threads[i],NULL);
}

您正在创建一个线程,然后立即加入它,等待它完成。这导致十个线程按顺序创建而不是并行创建,从而允许回收它们的 ID。

如果您在加入之前创建所有十个线程,您会看到不同的 ID。

for(int i=0;i<10;i++){
    report[i] = pthread_create(&threads[i],NULL,message,(void*)i);
}

for(int i=0;i<10;i++){
    pthread_join(threads[i],NULL);
}

关于c - 多个线程如何拥有相同的线程ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46469399/

相关文章:

c - 知识树中的段错误

c - 在 C 中如何将数组名转换为数组指针?

c - 使用 __builtin_popcount 或其他内在函数来处理 _mm256_movemask_pd 比较位图的结果?

multithreading - C++11 中的动态内存分配是线程安全的吗?

linux - Docker 运行 - 用户组没有按预期工作?

mysql - MariaDB 安装后没有提示密码

c - 是否(不)可以在 C 源代码中使用特殊字符?

java - 不变性和可重载配置

java - AsyncTask 卡住其线程和 UI 线程

ubuntu - Jenkins 无法访问