我目前正在尝试学习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;
}
为什么?
您的代码没有任何问题,只要您确保在加入线程之前ID0
和ID1
不会超出范围,并且任何一个线程都不会在没有适当同步的情况下修改ID0
和ID1
。
通常,将实体传递给不大于(void*)
的线程时,按值传递它是[[更安全,如下所示:
pthread_create(&tid, NULL, fn, (void*)ID0);
以这种方式完成后,ID0
可以超出范围,而没有新线程将访问悬挂堆栈的危险,也没有发生数据争用的危险(这是未定义的行为)。