如何正确删除指向回调函数的指针

How to properly delete a pointer to callback function.

本文关键字:函数 指针 回调 何正确 删除      更新时间:2023-10-16
  1. 我有一个MainProgram.exe,它调用MyDll.dll并使用curl接收回调函数上的数据
  2. 我已经将curl封装在一个名为CurlGetData的函数中,该函数创建了一个curl实例并执行curl_easy_perform

这是我的代码:

//Interface class to derive from
class  ICurlCallbackHandler
{
public:
    virtual size_t CurlDataCallback( void* pData, size_t tSize ) = 0;
};
//Class that implements interface
class CurlCallbackHandler : public ICurlCallbackHandler
{
public:
    bool m_exit = false;
    virtual size_t CurlDataCallback( void* pData, size_t tSize ) override
    {
        if(m_exit)
            return CURL_READFUNC_ABORT;
       // do stuff with the curl data
        return tSize;
    }
}

CurlCallbackHandler *m_curlHandler;
//Create an instance of above class in my dll constructor
MyDll:MyDll()
{
    m_curlHandler = new CurlCallbackHandler();
}
//Cleanup above class in my dll destructor
MyDll:~MyDll()
{
    delete m_curlHandler;
    m_curlHandler = nullptr;
}
//Function to start receiving data asynchronously  
void MyDll::GetDataAsync()
{
    std::async([=]
    {
        //This will receive data in a new thread and call CurlDataCallback above
        //This basically calls easy_perform
        CurlGetData(m_curlHandler);
    }
}
//Will cause the curl callback to return CURL_READFUNC_ABORT
void MyDll::StopDataAsync()
{
    m_curlHandler->m_exit = true;
}

函数GetDataAsync是从我的主程序中调用的,它基本上调用curl_easy_performer,并使用m_curlHandler作为其回调函数,该函数调用回CurlDataCallback。

这一切都很好,但每当我的主程序退出时,它都会调用MyDll::StopDataAsync来停止curl数据回调,然后调用MyDll的析构函数来清理m_curlHandler。

但我发现,在那一刻,curl还没有完成这个回调,程序崩溃了,因为m_curlHandler已经被删除,但新异步线程中的curl回调仍在使用它。

有时它关闭得很好,但有时由于curlcallback试图访问已被析构函数删除的指针而崩溃。

如何最好地清理m_curlHandler?我想避免等待超时,因为这会影响我的主程序的性能。

根据C++标准,MyDll::GetDataAsync()函数不应该立即返回,它应该阻塞直到异步线程完成,这将有效地使操作同步。然而,我认为Microsoft故意违反了std::async规范的这一部分,所以实际上它确实会立即返回,并且当异步线程仍在使用回调时,您可能会破坏回调(如果Microsoft实现遵循标准,这正是可以避免的问题!)

解决方案是保持std::async返回的std::future,然后在销毁回调之前阻止该未来(这确保异步线程已经完成)。

class MyDLL
{
    std::future<void> m_future;
    ...
};
MyDll:~MyDll()
{
    StopDataAsync();
    m_future.get();        // wait for async thread to exit.
    delete m_curlHandler;  // now it's safe to do this
}
//Function to start receiving data asynchronously  
void MyDll::GetDataAsync()
{
    m_future = std::async([=]
    {
        //This will receive data in a new thread and call CurlDataCallback above
        //This basically calls easy_perform
        CurlGetData(m_curlHandler);
    }
}

注意:你的m_exit成员应该是std::atomic<bool>(或者你应该使用互斥来保护对它的所有读写),否则你的程序会有数据竞争,因此会有未定义的行为。

对于m_curlHandler,我也会使用std::unique_ptr<CurlCallbackHandler>

我想避免等待超时,因为这会影响我的主程序的性能。

上面的解决方案将导致析构函数等待,但仅等待回调注意到m_exit == true并导致异步线程停止运行所需的时间。这意味着你只需要等待必要的时间,而不是更长的时间,不像超时意味着猜测多长时间"足够长",然后可能会增加一点以确保安全。