2016-09-16 55 views
-2

您好我最近开始学习win32/opengl,并且我设法编写了一个在窗口中显示多色多维数据集的函数。我的问题是有一个资源泄漏,但我很难过,不知道我忘了什么忘记删除。资源泄露opengl/win32

注意我已经把范围缩小是这个函数中

void display() 
{ 
    g.hglrc = wglCreateContext(g.hdc); 
    wglMakeCurrent(g.hdc, g.hglrc); 

    // make the color a white hue 
    glClearColor(1.0F, 1.0F, 1.0F, 1.0F); 

    // Clear screen and Z-buffer 
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

    // Reset transformations 
    glLoadIdentity(); 

    // Rotate when user changes rotate_x and rotate_y 
    glRotatef(rotate_x, 1.0, 0.0, 0.0); 
    glRotatef(rotate_y, 0.0, 1.0, 0.0); 

    //Multi-colored side - FRONT 
    glBegin(GL_POLYGON); 
    glColor3f(1.0, 0.0, 0.0);  glVertex3f(0.5, -0.5, -0.5);  // P1 is red 
    glColor3f(0.0, 1.0, 0.0);  glVertex3f(0.5, 0.5, -0.5);  // P2 is green 
    glColor3f(0.0, 0.0, 1.0);  glVertex3f(-0.5, 0.5, -0.5);  // P3 is blue 
    glColor3f(1.0, 0.0, 1.0);  glVertex3f(-0.5, -0.5, -0.5);  // P4 is purple 
    glEnd(); 

    // White side - BACK 
    glBegin(GL_POLYGON); 
    glColor3f(1.0, 1.0, 1.0); 
    glVertex3f(0.5, -0.5, 0.5); 
    glVertex3f(0.5, 0.5, 0.5); 
    glVertex3f(-0.5, 0.5, 0.5); 
    glVertex3f(-0.5, -0.5, 0.5); 
    glEnd(); 

    // Purple side - RIGHT 
    glBegin(GL_POLYGON); 
    glColor3f(1.0, 0.0, 1.0); 
    glVertex3f(0.5, -0.5, -0.5); 
    glVertex3f(0.5, 0.5, -0.5); 
    glVertex3f(0.5, 0.5, 0.5); 
    glVertex3f(0.5, -0.5, 0.5); 
    glEnd(); 

    // Green side - LEFT 
    glBegin(GL_POLYGON); 
    glColor3f(0.0, 1.0, 0.0); 
    glVertex3f(-0.5, -0.5, 0.5); 
    glVertex3f(-0.5, 0.5, 0.5); 
    glVertex3f(-0.5, 0.5, -0.5); 
    glVertex3f(-0.5, -0.5, -0.5); 
    glEnd(); 

    // Blue side - TOP 
    glBegin(GL_POLYGON); 
    glColor3f(0.0, 0.0, 1.0); 
    glVertex3f(0.5, 0.5, 0.5); 
    glVertex3f(0.5, 0.5, -0.5); 
    glVertex3f(-0.5, 0.5, -0.5); 
    glVertex3f(-0.5, 0.5, 0.5); 
    glEnd(); 

    // Red side - BOTTOM 
    glBegin(GL_POLYGON); 
    glColor3f(1.0, 0.0, 0.0); 
    glVertex3f(0.5, -0.5, -0.5); 
    glVertex3f(0.5, -0.5, 0.5); 
    glVertex3f(-0.5, -0.5, 0.5); 
    glVertex3f(-0.5, -0.5, -0.5); 
    glEnd(); 

    wglMakeCurrent(NULL, NULL); 

    SwapBuffers(g.hdc); 
    ReleaseDC(g.hwnd, g.hdc); 
    wglDeleteContext(g.hglrc); 
} 
+0

是什么让你觉得有“资源泄漏”? –

+0

如果我使用显示调用来运行程序,RAM的使用很容易达到100 MB,并继续增长。如果我删除了对此函数的调用,则无论运行多长时间,其使用率都保持在27-28mbs左右。所以我认为这是资源泄漏的结果,因为我没有看到任何会导致这种行为的东西。 –

+1

注释掉该功能的内容,确认问题已消失,然后逐渐取消注释某一行/部分,直到问题恢复。 –

回答

4
g.hglrc = wglCreateContext(g.hdc); 

不要那样做。

每次需要重新绘制屏幕时,都不会创建呈现上下文。你创建它一次;它应该只在您的窗口消失时消失。

现在,这并不一定是为什么创建和销毁渲染上下文会使资源闲置的原因。但这是无关紧要的;你不应该这样做,因为性能。渲染上下文的创建和销毁不是一个快速的过程,也不是它的目的。

+0

当然,如果我将它从功能中解放出来,但是资源泄漏仍然存在,那么您的工作就会显着提升性能。 –

+0

不仅仅是你指出的那条线,而是显示循环中的所有'wgl'调用,特别是底部附近的其他win32行,使当前上下文为空并释放DC无疑会导致资源浪费。 –