int main(int a, char *args[]) {
int i;
pthread_t threads[8];
unsigned int* pixmap = malloc(1024*1024*sizeof(int));
v_threadargs.height = 1024.0f;
v_threadargs.width = 1024.0f;
v_threadargs.pixmap = pixmap;
for (i = 0; i < 8; i++) {
v_threadargs.threadid = i;
pthread_create(&threads[i], NULL, render, (void *) &v_threadargs);
}
for (i = 0; i < 8; i++)
pthread_join(threads[i], NULL);
writetga(pixmap, 1024, 1024, "ray8out.tga");
free(pixmap);
pthread_exit(NULL);
return 0;
}
void *render(void *r_threadargs) {
int i,j, threadid, start;
float height, width;
int *pixmap;
struct s_threadargs *p_threadargs;
p_threadargs = (struct s_threadargs *) r_threadargs;
height = p_threadargs -> height;
width = p_threadargs -> width;
pixmap = p_threadargs -> pixmap;
threadid = p_threadargs -> threadid;
stepy = viewplaney0;
deltax = (viewplanex1 - viewplanex0) / width;
deltay = (viewplaney1 - viewplaney0) / height;
stepy += deltay;
float *viewer = (float[3]){0.0f, 0.0f, -7.0f};
if (threadid == 1)
start = 0;
else
start = threadid * height/8;
for (i = start; i < (threadid + 1)*(height/8); i++) {
stepx = viewplanex0;
for (j = 0; j < width; j++) {
float *color = (float[3]){0.0f, 0.0f, 0.0f};
float *raydir = (float[3]){stepx - viewer[0], stepy - viewer[1], 0 - viewer[2]};
float maxdist = 100000.0f;
normalize(raydir);
trace(raydir, viewer, color, 0,maxdist);
int r = (int)(roundf(color[0]*255.0f));
if (r > 255) { r = 255; }
int g = (int)(roundf(color[1]*255.0f));
if (g > 255) { g = 255; }
int b = (int)(roundf(color[2]*255.0f));
if (b > 255) { b = 255; }
pixmap[j+i*(int)width] = (r << 16) | (g << 8) | (b);
stepx += deltax;
}
stepy += deltay;
}
}
我正在尝试使用8个线程(使用gcc的pthreads)实现此光线跟踪器程序,但输出图像“ray8out.tga”不正确。程序正确执行,没有任何错误,但逻辑中缺少一些东西。如果有人请帮助我,那将是一种乐趣,错误在哪里?
答案 0 :(得分:3)
您将相同的threadargs结构传递给每个线程;没有保证他们会在你改变线程值之前开始运行。你应该为每个线程为malloc分配一个新的threadargs结构(并在新线程中释放它)。