简体   繁体   中英

OpenCL - C++ wrapper - Context deinitialization in dynamic library leads to access violation

I want to build a library (shared library on a windows system) which provides some default configurations (context,command queues, ...). The problem is that I get an access violation when the application tries to exit. My first guess was that it might be a problem with my wrapper implementation but then I've built up a test case which uses the official C++ wrapper ( cl.hpp ).

In the shared library

boost::optional<cl::Context> cpuContext;
void cpu() {
    cpuContext = cl::Context(CL_DEVICE_TYPE_CPU);
}

On the applcation side

int main(int argc, char** argv) {
    cpu();
}

So pretty simple stuff...

The interesting thing is that this happens only with the Intel runtime (can't test for Intel GPUs) but not with the runtime provided by Nvidia. It also doesn't happen if the cpuContext variable is declared on the application side.

So my question is:
Is this a bug in the Intel runtime or have I missed something and ran into undefined behavior?

There's a potential for an very subtle issue if you try to release an OpenCL object from a DllMain. It can show the behavior you are seeing, but can be somewhat unpredictable or intermittent. First, a little background:

When you load OpenCL.dll, on most platforms you are loading a standardized Installable Client Driver (ICD) that is a shim between your code and the various implementations that might exist on your system. You can read more about it here . The ICD is a DLL that uses the Windows LoadLibrary call to load the DLLs provided by the OpenCL vendor (Intel, AMD, etc.).

Using LoadLibrary does not update Windows DLL dependency tracking structures. So when the process shuts down, there is no way to know the order in which such DLLs will be unloaded. In this case, the vendor-supplied OpenCL DLLs could have already been unloaded by the time the destructor for your your global OpenCL context object is called. This has the potential to cause an access violation. You can read more about that here .

Given all of this, I would avoid designing a DLL that requires OpenCL functions be called in global object destructors or DllMain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM