2011-06-01 130 views
0
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並行線程)這光線跟蹤程序,但輸出圖像「ray8out.tga」是不正確的。程序正確執行沒有任何錯誤,但邏輯中缺少某些內容。如果有人能夠幫助我,那會很高興,錯誤在哪裏?使用光線跟蹤並行線程

回答

3

你正在向每個線程傳遞相同的threadargs結構;沒有保證他們會在更改threadid值之前開始運行。您應該爲每個線程分配一個帶有malloc的新線程結構(並從新線程本身中釋放它)。

+0

其實我是一個新的線程。你的意思是: (i = 0; i <8; i ++){ v_threadargs [i] .height = 1024.0f; v_threadargs [i] .width = 1024.0f; v_threadargs [i] .pixmap = pixmap; v_threadargs [i] .threadid = i; pthread_create(&threads [i],NULL,render,(void *)&v_threadargs [i]); } – 2011-06-05 21:57:08

+0

@Bilal,是的,使用數組是一個選項,只要v_threadargs一直存在,直到所有線程連接在一起。 – bdonlan 2011-06-07 20:28:01