我已经制作了2个线程并使用线程函数计算PI的值。我试图将线程函数的值返回到main(以计算PI为例),但它没有给我正确的答案。每当我运行它时,线程函数的cout语句给出了正确的答案,但是在取消引用void *运算符时我没有得到相同的结果。这是我的代码:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>
#include<string>
#include<math.h>
using namespace std;
class ThreadObj
{
public:
int n;
float flag;
};
void* Func(void* param)
{
float num, den,partialN;
float partialSum = 0;
ThreadObj* obj1 = (ThreadObj*)param;
num = obj1->flag;
partialN = obj1->n;
for ( int i=0; i<partialN; i++)
{
if(num==1)
{
den = 4*i + 1;
}
else
{
den = 4*i+3;
}
partialSum = partialSum + (num/den);
}
cout<<"Answer of Thread's execution is: "<<partialSum<<endl;
//Returning the answer and casting it into appropriate datatype (void*)
void* ReturnPointer;
ReturnPointer = &partialSum;
return ReturnPointer;
//return (void*) partialSum;
//return partialSum;
}
int main()
{
float n;
float sum=0;
cout<< "Enter number of iteration: "<<endl;
cin>> n;
pthread_t Thread1, Thread2;
//Use 1st Thread to calculate the +ve terms
ThreadObj obj1;
obj1.n = n/2;
obj1.flag = 1.0;
pthread_create(&Thread1,NULL,&Func, &obj1);
//Use 2nd Thread to calculate the -ve terms
ThreadObj obj2;
obj2.n = n/2;
obj2.flag = -1.0;
pthread_create(&Thread2,NULL,&Func, &obj2);
//Getting value from both threads
float PartialSum1=0, PartialSum2=0;
void* p1 = &PartialSum1;
void* p2 = &PartialSum2;
//pthread_join(Thread1,NULL);
pthread_join(Thread2, (void**) p1);
pthread_join(Thread1, (void**) p2);
cout<<endl<<"Partial Sum2 is: "<<PartialSum2<<endl;
cout<<endl<<"Partial Sum1 is: "<<PartialSum1<<endl;
sum = PartialSum1 + PartialSum2;
sum = sum * 4;
cout<< "Value of PI: "<<sum;
cout<<endl;
return 0;
}
示例输出为:
输入迭代次数: 100
线程执行的答案是:-1.25072 线程执行的答案是:2.03362
部分Sum2是:-1.12921e-05
部分Sum1是:-5.64419e-06 PI值:-6.77452e-05
答案 0 :(得分:6)
您正在返回一个指向超出函数末尾范围的局部变量的指针。这是未定义的行为,你得到垃圾就是这样的结果。
我建议你不应该返回void*
,而应该将另一个参数传递给函数并将结果放入其中。