C 线程编程。。。终端没有输出
我正在做线程编程,并试图实现MonteCarlo技术来计算其中的Pi值。我编译了代码,没有错误,但是当我执行时,我没有得到它的输出。如果有什么错误,请纠正我 这是我的密码:C 线程编程。。。终端没有输出,c,linux,C,Linux,我正在做线程编程,并试图实现MonteCarlo技术来计算其中的Pi值。我编译了代码,没有错误,但是当我执行时,我没有得到它的输出。如果有什么错误,请纠正我 这是我的密码: #include <stdio.h> #include <stdlib.h> #include <time.h> #include <pthread.h> #define frand() ((double) rand() / (RAND_MAX)) #define MAX_L
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define frand() ((double) rand() / (RAND_MAX))
#define MAX_LEN 1353
const size_t N = 4;
float circlePoints=0;
void* point_counter(void *param){
float xcord;
float ycord;
while(MAX_LEN){
xcord=frand();
ycord=frand();
float cord = (xcord*xcord) + (ycord*ycord);
if(cord <= 1){
circlePoints++;}
}
}
int main()
{
printf("out");
size_t i;
pthread_t thread[N];
srand(time(NULL));
for( i=0;i <4;++i){
printf("in creating thread");
pthread_create( &thread[i], NULL, &point_counter, NULL);
}
for(i=0;i <4;++i){
printf("in joining thread");
pthread_join( thread[i], NULL );
}
for( i=0;i <4;++i){
printf("in last thread");
float pi = 4.0 * (float)circlePoints /MAX_LEN;
printf("pi is %2.4f: \n", pi);
}
return 0;
}
#包括
#包括
#包括
#包括
#定义frand()((双)rand()/(rand_MAX))
#定义最大长度1353
常数大小N=4;
浮点数=0;
无效*点计数器(无效*参数){
浮点数;
浮动ycord;
while(MAX_LEN){
xcord=frand();
ycord=frand();
浮子线=(xcord*xcord)+(ycord*ycord);
如果(cord您在此处遇到无限循环:
while(MAX_LEN){
因为MAX_LEN
是并保持非零
至于为什么在此之前没有看到任何输出,请参见您的线程函数中有一个无限循环:
while(MAX_LEN){
...
}
因此,您创建的所有线程都不会出现该循环
另外,circlePoints
被所有线程修改,这将导致争用条件()并可能导致值不正确。您应该使用互斥锁来避免它。没有输出,是指它在无限循环中运行吗?您考虑过使用调试器吗?它很容易显示无限循环
while(any_non_zero_number_which does_not_update)
{
infinite loop //not good unless you intend it that way
}