我目前正在尝试学习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?
只要您确保在加入线程之前
ID0
和ID1
不超出范围,并且任何一个线程都不会在没有适当同步的情况下修改ID0
和ID1
,那么代码就没有问题。通常,将实体传递到不大于
(void*)
的线程中时,按值传递实体是更安全的,如下所示:pthread_create(&tid, NULL, fn, (void*)ID0);
当这样做时,
ID0
可以超出范围,而没有新线程将访问悬挂堆栈的危险,也没有数据争用的危险(这是未定义的行为)。
关于c++ - 为什么通过以下方式将ID传递给线程很不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61920647/