我刚开始学习多线程,我知道示例应用程序--我正在做的--在使用线程时甚至会降低性能。使用的编译器是GCC4.7,带有以下标志:-std=c++0x -g -O3 -Wall
因此,我正在使用C++11并使用std::线程实现。一般来说,我试图开发跨平台,所以我在Windows上开发大学计算机上的GCC4.7以及Ubuntu/Mac在我的家用机器上。为了能够处理跨平台的窗口创建,我使用了SFML-库(2.0)。
这里是简化的CApp类和相关函数:
class CApp
{
public:
//! Constructor.
CApp(void);
//! Deconstructor.
~CApp(void);
/* Public Functions: */
//! Initializer function, needs to be called before Run-Function to allocate everything and set everything up.
bool Initialize(unsigned int width, unsigned int height, char* title, bool vsync, CState* startState);
void Run(void); //!< Starts the game-loop
private:
void ProcessEvent(sf::Event event);
sf::RenderWindow* m_pWindow; //!< window instance
std::vector<std::thread> m_threads;
};一般来说,我的应用程序是一个小型的OpenGL演示场景,它应该是大量多线程的,以便能够对多线程适合的地方和不适合的地方进行测试和比较。
相关职能的实现:
void CApp::Run(void)
{
while (m_pWindow->IsOpen())
{
sf::Event event;
while (m_pWindow->PollEvent(event))
{
m_threads.push_back(std::thread(&CApp::ProcessEvent, this, event));
}
// ...
m_threads.clear();
}
}
void CApp::ProcessEvent(sf::Event event)
{
if (event.Type == sf::Event::Closed)
m_pWindow->Close();
if (event.Type == sf::Event::KeyPressed)
{
if (event.Key.Code == sf::Keyboard::Escape)
m_pWindow->Close();
}
}我得到的运行时错误只是第一帧上的一个中止陷阱:6:“终止调用而没有活动异常-程序接收信号SIGABRT,在__pthread_kill ()"_中中止. 0x00007fff8fdf4ce2
如果我超出了线程创建的注释,只需在当前线程中调用ProcessEvent,就不会出现问题,所以问题必须与线程相关。
SFML并不是所有线程都是安全的,所以我假设问题是m_pWindow-指针或事件本身作为函数参数,但是如何解决这个问题呢?
发布于 2012-04-19 11:32:15
在清除向量和删除所有线程之前,绝对应该等待所有线程完成:
void CApp::Run(void)
{
while (m_pWindow->IsOpen())
{
sf::Event event;
while (m_pWindow->PollEvent(event))
{
m_threads.push_back(std::thread(&CApp::ProcessEvent, this, event));
}
for(auto& i : m_threads)
i.join();
m_threads.clear();
}
}此外,当您使用GCC时,我建议使用-pthread选项进行编译。
https://stackoverflow.com/questions/10226716
复制相似问题