首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >并发事件处理问题

并发事件处理问题
EN

Stack Overflow用户
提问于 2012-04-19 11:06:44
回答 1查看 296关注 0票数 1

我刚开始学习多线程,我知道示例应用程序--我正在做的--在使用线程时甚至会降低性能。使用的编译器是GCC4.7,带有以下标志:-std=c++0x -g -O3 -Wall

因此,我正在使用C++11并使用std::线程实现。一般来说,我试图开发跨平台,所以我在Windows上开发大学计算机上的GCC4.7以及Ubuntu/Mac在我的家用机器上。为了能够处理跨平台的窗口创建,我使用了SFML-库(2.0)。

这里是简化的CApp类和相关函数:

代码语言:javascript
复制
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演示场景,它应该是大量多线程的,以便能够对多线程适合的地方和不适合的地方进行测试和比较。

相关职能的实现:

代码语言:javascript
复制
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-指针或事件本身作为函数参数,但是如何解决这个问题呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-19 11:32:15

在清除向量和删除所有线程之前,绝对应该等待所有线程完成:

代码语言:javascript
复制
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选项进行编译。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10226716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档