5

Since I'm having suspicions the "black box" (GPU) is not shutting down cleanly in some larger code (others perhaps too), I would include a cudaDeviceReset() at the end of main(). But wait! This would Segmentation fault all instances of classes statically created in main() with non-trivial CUDA code in destructors, right? E.g.

class A {
public:
  cudaEvent_t tt;
  cudaEvent_t uu;
  A() { 
    cudaEventCreate(&tt);
    cudaEventCreate(&uu);
  }
  ~A(){  
    cudaEventDestroy(tt);
    cudaEventDestroy(uu);
  }
};

instantiated statically:

int main() {
  A t;
  cudaDeviceReset();
  return 0;
} 

segfaults on exit. Question: is perhaps cudaDeviceReset() invoked automatically on exit from main()?

Otherwise whole useful code of main() should be shifted to some run(), and cudaDeviceReset() should be the as last command in main(), right?

Community
  • 1
  • 1
P Marecki
  • 1,108
  • 15
  • 19
  • 2
    cudaDeviceReset explicitly destroys any context on the active device being held by process or thread that calls it. But that it all it does. If you have CUDA API calls which need a context to work in destructor code, then you can't have them called after the context is already destroyed (and it will be destroyed automatically by the runtime when the process terminates). – talonmies Jul 23 '12 at 09:15

1 Answers1

3

As indicated by Talonmies, the destructor of class A is called after the cudaDeviceReset() function is already called, namely when the main(..) function finishes.

I think, you may take cudaDeviceReset() to an atexit(..) function.

void myexit() {
  cudaDeviceReset();
}

int main(...) {
  atexit(myexit); 
  A t;
  return 0;
}
Vitality
  • 20,705
  • 4
  • 108
  • 146
phoad
  • 1,801
  • 2
  • 20
  • 31
  • 1
    So you may try to take the declaration of "t" in another parenthesis. And then call cudaDeviceReset after the end of this paranthesis. So it may force the destruction of the "t" before the device reset.. """int main(..) { { A t; t.someoperation(); } cudaDeviceReset(); }""" – phoad Jun 03 '13 at 20:33
  • Thanks. I think it is a good point. I will check as soon as I can and let you know. – Vitality Jun 04 '13 at 20:18
  • There is an interesting discussion by Talonmies at [CUDA streams destruction and CudaDeviceReset](http://stackoverflow.com/questions/16979982/cuda-streams-destruction-and-cudadevicereset/16982503?noredirect=1#comment24536013_16982503) on this topic. – Vitality Jun 07 '13 at 15:04
  • Yes, Talonmies is the king especially if the topic is CUDA. I really curious which CUDA related questions he has answered. Lets see. Thanks Talonmies. – phoad Jun 07 '13 at 17:28