2012-02-09 68 views
0

我正在研究c中的項目,在那裏我要做一些重要的物理計算,並且我希望能夠在完成時看到結果。現在它的工作方式是我在主線程上運行GLUT,並使用單獨的線程(pthread)來執行輸入(從終端)和計算。我目前使用glutTimerFunc來做動畫,但問題是無論發生什麼,該函數都會觸發每個給定的時間間隔。我可以通過在動畫函數中使用if語句停止動畫,停止變量被updatet,但是這會使用大量不必要的資源(我認爲)。開始和停止GLUT動畫

要解決這個問題,我想我可以使用一個額外的線程與自定義計時器功能,我可以控制自己(沒有glutMainLoop搞砸了)。目前這是我的測試函數來檢查這是否可行(意思是函數本身沒有完成)。它運行在一個單獨的線程createt只是glutMainLoop前:

void *threadAnimation() { 
    while (1) { 
     if (animationRun) { 
      rotate = rotate+0.00001; 
      if (rotate>360) { 
       rotate = rotate-360; 
      } 

      glutSetWindow(window); 
      glutPostRedisplay(); 
     } 
    } 
} 

我的具體問題是,動畫只運行了幾秒鐘,然後停止。有人知道我能如何解決這個問題嗎?我打算稍後使用計時器等,但是我正在尋找的方法是確保將glutPostRedisplay發送到正確的位置。我買了glutSetWindow(窗口)是解決方案,但顯然不是。如果我刪除glutSetWindow(窗口)動畫仍然工作,只是不是很長,但運行速度快得多(所以也許glutSetWindow(窗口)需要大量的資源?)

btw變量「窗口」是這樣創建的:

glutInit(&argc, argv); 
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); 
glutInitWindowSize(854, 540); 
glutInitWindowPosition(100, 100); 
window = glutCreateWindow("Animation View"); 
init(); 
glutDisplayFunc(display); 
glutReshapeFunc(reshape); 
timerInt = pthread_create(&timerThread, NULL, &threadAnimation, NULL); 
glutMainLoop(); 

我不真的知道這是否正確,但它編譯得很好。任何幫助非常appriciated!

回答

0

這裏有一個小想法,創建類,將包含所有動態設置:

class DynamicInfo { 
    public int vertexCount; 
    public float *vertexes; 

    ... 

    DynamicInfo &operator=(const DynamicInfo &origin); 
}; 

而不是主要的應用將包含這些:

DynamicInfo buffers[2]; 
int activeBuffer = 0; 

在動畫線程只畫(也許還可以利用一些線程鎖一個變量):

DynamicInfo *current = buffers + activeBuffer; // Or rather use reference 

在計算中:

// Store currently used buffer as current (for future manipulation) 
DynamicInfo *current = buffers + activeBuffer; 

// We finished calculations on activeBuffer[1] so we may propagate it to application 
activeBuffer = (activeBuffer + 1)%2; 

// Let actual data propagate to current buffer 
(*current) = buffers[activeBuffer]; 

它再次鎖定一個變量。