与SFML一起使用时,C ++ std :: thread会产生分段错误错误

时间:2020-08-19 13:23:05

标签: c++ multithreading c++11 segmentation-fault sfml

我正在尝试使用SFML开发多线程游戏。 我从SFML official website编译了下面的代码。

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

效果很好。当我修改代码以使用如下所示的线程时,发生了问题。

#include <SFML/Graphics.hpp>
#include <thread>
#include <iostream>

void Render(sf::RenderWindow& _window, sf::CircleShape& _shape)
{
    while (_window.isOpen())
    {
        sf::Event event;
        while (_window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                std::cout << "Closing window...\n";
                _window.close();
            }
        }

        _window.clear();
        _window.draw(_shape);
        _window.display();
    }
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    std::thread renderThread(Render, std::ref(window), std::ref(shape));

    renderThread.join();

    return 0;
}

这段代码给了我

分段错误

关闭窗口时终端上的消息。

我想知道为什么这段代码会给我分段错误并修复错误。

0 个答案:

没有答案
相关问题