c++ - 为什么通过以下方式将ID传递给线程很不好?

标签 c++ linux multithreading pthreads posix

我目前正在尝试学习POSIX线程,并编写了可以在下面看到的简单代码。
有人告诉我,将ID传递给线程是很糟糕的,正如您在此代码段中所看到的:

    int ID0= 0;
    int ID1 = 1;

    pthread_create(&thread_zero, NULL, thread_function, (void*)&ID0);
    pthread_create(&thread_one, NULL, thread_function, (void*)&ID1);

这是为什么?

另外,使用pthread_self会更好吗?

完整代码:
#include <iostream>
#include <pthread.h>
#include <unistd.h>

void *thread_function(void *arg)
{

  for(int i =0; i<=10;i++)
    {
        std::cout << "Hello # " << i<< " From thread : " <<*((int*)arg) << std::endl;
        sleep(1);
    }

std::cout <<"Thread "<<*((int*)arg)<< " terminates" << std::endl;

pthread_exit(NULL);

}

int main(){
    pthread_t thread_zero;
    pthread_t thread_one;

    int ID0= 0;
    int ID1 = 1;

    pthread_create(&thread_zero, NULL, thread_function, (void*)&ID0);
    pthread_create(&thread_one, NULL, thread_function, (void*)&ID1);

    std::cout << "main: Creating threads" << std::endl;
    std::cout << "main: Wating for threads to finish" << std::endl;

    pthread_join(thread_zero, NULL);
    pthread_join(thread_one, NULL);

    std::cout<<"Main: Exiting"<<std::endl;
    return 0;
}

最佳答案

Why is that?



只要您确保在加入线程之前ID0ID1不超出范围,并且任何一个线程都不会在没有适当同步的情况下修改ID0ID1,那么代码就没有问题。

通常,将实体传递到不大于(void*)的线程中时,按值传递实体是更安全的,如下所示:
pthread_create(&tid, NULL, fn, (void*)ID0);

当这样做时,ID0可以超出范围,而没有新线程将访问悬挂堆栈的危险,也没有数据争用的危险(这是未定义的行为)。

关于c++ - 为什么通过以下方式将ID传递给线程很不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61920647/

相关文章:

c++ - 字符串 vector 到 istringstream

c++ - 构造函数初始化列表中的 'this'指针

.net - 以多线程方式运行 nUnit 测试

python - Flask 服务器退出时线程仍然运行

multithreading - 如何使用线程在 C# 中一个接一个地运行 3 个方法?

c++ - 在 C++ 中将字符串转换为 float

c++ - 模板函数的实例化点在调用点之后,编译器如何查找和链接它?

windows - Linux上.Net的潜在问题是什么

c - 实现文件描述符

linux - 即使删除了所有相关的 rpm,进程是否仍应运行?