我正在尝试让一个简单的多线程 OpenGL 应用程序正常工作。我有一个更新线程和一个渲染线程。按照我写它们的方式,它们本质上应该是轮流运行,因为它们是互斥锁的。相反,更新线程将运行数十次,然后渲染线程将运行数十次。以下是相关代码:
void glRender() {
printf("glRender()\n");
glXMakeCurrent(display, window, glXContext);
glSetup();
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glVertex2f(cosf(fDrawAngle), sinf(fDrawAngle));
glVertex2f(cosf(fDrawAngle+2.1f), sinf(fDrawAngle+2.1f));
glVertex2f(cosf(fDrawAngle+4.2f), sinf(fDrawAngle+4.2f));
glEnd();
glXSwapBuffers(display, window);
glXMakeCurrent(display, 0, 0);
}
void * glThread(void * params) {
while (bRunning) {
pthread_mutex_lock(&mutex);
glRender();
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
// Multi threaded version
void gameUpdateMT() {
while (bRunning) {
pthread_mutex_lock(&mutex);
printf("gameUpdate()\n");
windowUpdate();
fDrawAngle += 0.01f;
pthread_mutex_unlock(&mutex);
}
}
// Single threaded version - Runs fine.
void gameUpdateST() {
while (bRunning) {
printf("gameUpdate()\n");
windowUpdate();
fDrawAngle += 0.01f;
glRender();
}
}
gameUpdateMT() 和 glThread() 并行运行。是什么导致一个线程在另一个线程有机会运行之前循环了这么多次?