c++ - 多个线程无法访问同一个指针而不会出错

标签 c++ multithreading access-violation glfw

<分区>

我正在使用 GLFW3(窗口库)制作应用程序,我的操作系统是 Windows 8.1。

我的错误:我在我的主线程中创建了一个指针,而窗口的线程得到一个 access violation。当它尝试使用它时。

在我的应用程序中,我试图制作一个输入处理程序类,它从窗口接收事件并将它们发送到订阅该事件的所有对象。

为此,我让所有想要监听的对象继承 InputListener:

class InputListener{
public:
    virtual void onKeyDown(int key) = 0;
};

要订阅一个事件,一个对象必须使用一个伪全局(传递给构造类的引用)包装器变量,它包含我的InputHandler:

// My global wrapper
#include "InputHandler.h"
class Centrum{
public:
    InputHandler inputHandler;
public:
    Centrum(){}
};

输入处理器

class InputHandler{
    private:
        unsigned numEvents;
        InputListener* key_down; // Only trying to test on one subscriber for now.
    public:
        InputHandler();
        void registerKeyDown(InputListener* listener, int key);
        void key_event(int key, int action); // Is indirectly called by glfw window (same thread though)
};

// Implementation
InputHandler::InputHandler(){
    numEvents = 0;
}

void InputHandler::registerKeyDown(InputListener* listener, int key){
    // This is called from my main thread
    key_down = listener;
    key_down->onKeyDown(key); // Properly calls function on my Camera class which inherits InputListener
    numEvents++;
    printf("yes %u\n", numEvents);

}

void InputHandler::key_event(int key, int action){
    // This is called by the window's thread (glfw automatically makes this thread)
    printf("failure %u\n", numEvents); // Properly prints out numEvents
    key_down->onKeyDown(key);         // Runtime error here, access violation
}

订阅输入的例子:

Camera::Camera(Centrum& g_centrum){
    this->g_centrum = g_centrum;
    [...]
    g_centrum.inputHandler.registerKeyDown(this, GLFW_KEY_W);

}

最佳答案

被指向的变量在可以使用之前就已经死了。因此,当线程尝试使用它时,会引发运行时错误。

关于c++ - 多个线程无法访问同一个指针而不会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27525902/

相关文章:

c++ - shared_ptr 和引用计数器

windows - QueryWorkingSet 在其结果中包含无效页面

delphi - 读取任意内存位置?可能的?

将 SDL_ttf 与 SDL 和 SDL2 一起使用时出现 C++ 访问冲突

C++实体组件系统和使用模板访问组件

c++ - 在 OpenCV 中捕获和显示视频

c++ - Rand 在从最大为 75 的数字 (36) 开始时如何工作

c# - 为什么使用 Dispatcher.CurrentDispatcher.BeginInvoke 不更新我的 GUI 而使用 BeginInvoke 却可以?

python - 避免重复结果 多线程 Python

c++ - 将数据结构传递给不同的线程