SFML线程同步?
SFML thread synchronization?
我是 SFML 的新手,一直在尝试拥有一个多线程游戏系统(主线程上的所有游戏逻辑,以及使用 sf::Thread 在专用线程中渲染;主要用于练习线程)如解释的那样 in this page("Drawing with threads" 部分):
不幸的是,我的程序在 update() 期间的处理时间很长,使渲染过程完全失控,显示一些帧已绘制,而另一些帧完全为空。如果不是很明显,我的渲染线程正在尝试绘制甚至没有计算的东西,留下这种癫痫效果。
我要找的是让线程只在主逻辑计算完成后才渲染。这是我到目前为止得到的:
void renderThread()
{
while (window->isOpen())
{
//some other gl stuff
//window clear
//window draw
//window display
}
}
void update()
{
while (window->isOpen() && isRunning)
{
while (window->pollEvent(event))
{
if (event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
isRunning = false;
}
else if (m_event.type == sf::Event::Resized)
{
glViewport(0, 0, m_event.size.width, m_event.size.height);
}
}
// really resource intensive process here
time = m_clock.getElapsedTime();
clock.restart().asSeconds();
}
}
提前致谢。
我猜这些错误的发生是因为您操作了同时并行渲染的元素。您需要研究互斥体。
互斥锁锁定您要操作的元素(或在另一个线程中绘制),只要操作需要并在之后释放它。
当元素被锁定时,其他线程无法访问它。
伪代码示例:
updateThread(){
renderMutex.lock();
globalEntity.manipulate();
renderMutex.unlock();
}
renderThread(){
renderMutex.lock();
window.draw(globalEntity);
renderMutex.unlock();
}
我是 SFML 的新手,一直在尝试拥有一个多线程游戏系统(主线程上的所有游戏逻辑,以及使用 sf::Thread 在专用线程中渲染;主要用于练习线程)如解释的那样 in this page("Drawing with threads" 部分):
不幸的是,我的程序在 update() 期间的处理时间很长,使渲染过程完全失控,显示一些帧已绘制,而另一些帧完全为空。如果不是很明显,我的渲染线程正在尝试绘制甚至没有计算的东西,留下这种癫痫效果。
我要找的是让线程只在主逻辑计算完成后才渲染。这是我到目前为止得到的:
void renderThread()
{
while (window->isOpen())
{
//some other gl stuff
//window clear
//window draw
//window display
}
}
void update()
{
while (window->isOpen() && isRunning)
{
while (window->pollEvent(event))
{
if (event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
isRunning = false;
}
else if (m_event.type == sf::Event::Resized)
{
glViewport(0, 0, m_event.size.width, m_event.size.height);
}
}
// really resource intensive process here
time = m_clock.getElapsedTime();
clock.restart().asSeconds();
}
}
提前致谢。
我猜这些错误的发生是因为您操作了同时并行渲染的元素。您需要研究互斥体。 互斥锁锁定您要操作的元素(或在另一个线程中绘制),只要操作需要并在之后释放它。 当元素被锁定时,其他线程无法访问它。
伪代码示例:
updateThread(){
renderMutex.lock();
globalEntity.manipulate();
renderMutex.unlock();
}
renderThread(){
renderMutex.lock();
window.draw(globalEntity);
renderMutex.unlock();
}