我使用 C 语言中的 POSIX 线程库制作了 Mandelbrot 集视觉演示。输出是一个 .pgm 文件。 在线程实现时,似乎弹出了三种情况,如下所示:-
那么,使用更少的线程还是使用那些 CPU 使用率达到 100% 的线程或使用操作系统提供的最大线程数是否明智?
我使用的是 Intel Pentium 4 x86(2GB RAM)机器和 Windows 7 Ultimate。
参考代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#define MAX_ITR 100
#define MAX_UNSTABLE 4
#define Xin -1.5
#define Yin 1.0
#define Xf 0.5
#define Yf -1.0
char * arr;
void * function(void * arg)
{
int width = *((int *)arg);
int height = 8000;
int count;
double x=Xin, y=Yin;
double xf = Xf, yf = Yf;
double xinc = (xf-x)/(double)8000;
double yinc = (yf-y)/(double)8000;
double rr,ii,zr=0,zi=0,mag=0;
int i,j;
for(i=0;i<height;i++,x=Xin + xinc*width,y+= yinc)
{
for(j=0+width;j<width+400;j++,x += xinc,count=-1,zr=0,zi=0)
{
mag=0;
while((++count < MAX_ITR) && (mag < MAX_UNSTABLE))
{
rr = zr;
ii = zi; // square of Z
zr = rr*rr - ii*ii;
zi = 2*rr*ii;
zr += x;
zi += y;
mag = pow(zr*zr + zi*zi,0.5);
}
arr[j + i * height] = 255 - (int)(count * 255/MAX_ITR);
}
}
printf("\nthread id >%d\n",width/400 + 1);
printf("xinc %f\nyinc %f\n",xinc,yinc);
printf("from=>(%11.9f, %11.9f)\nto=>(%11.9f, %11.9f)\n",xinc*width,Yin,2*(xinc*width),Yf);
pthread_exit(NULL);
return NULL;
}
int main()
{
int width = 8000, height = 8000,i;
arr = (char *)malloc(sizeof(char) * width * height);
pthread_t threadPoll[20];
int set[20] = {0};
for(i=0;i<20;i++)
{
set[i] = 400*i;
printf("%d ",set[i]);
}
printf("\n");
for(i=0;i<20;i++)
{
pthread_create(&(threadPoll[i]), NULL, function, &(set[i]));
}
for(i=19;i>0;i--)
{
pthread_join(threadPoll[i],NULL);
}
FILE * fp = (FILE*)fopen("out.pgm","wb");
if(fp == NULL)return 1;
fprintf(fp,"P5\n%d %d\n255\n",width,height);
fwrite(arr,sizeof(char)*width*height,1,fp);
fclose(fp);
printf("done!");
free(arr);
return 0;
}