kunzmi / managedCuda

ManagedCUDA aims an easy integration of NVidia's CUDA in .net applications written in C#, Visual Basic or any other .net language.
Other
440 stars 79 forks source link

PrimaryContext: implicitly invokes the constructor of CudaContext #33

Closed jklj077 closed 7 years ago

jklj077 commented 7 years ago

Hi, Thanks for your work!

I was having some problems when using the PrimaryContext class. From the timeline produced by Visual Profiler, it seemed that each time I referenced a primary context (created a PrimaryContext class), a new context was created, which is not how it's supposed to do. From what I understand, it should create a context only when there is none on the device and should reference the context if there is one.

What I found after examining the code is that it seems currently the PrimaryContext class inherits from the CudaContext class. When a PrimaryContext is created, its base class constructor is invoked, which is public CudaContext(): this(0, CUCtxFlags.SchedAuto, true) {...} , which is public CudaContext(int deviceId, CUCtxFlags flags, bool createNew) {...} ,and a new context is then created.

I've fixed the problem in my local repo. However, the fix is rather ugly. To keep the inheritance, the base class constructor must do nothing, as all the logic needs is defined in the constructor of PrimaryContext. However, the base class (CudaContext) constructor is heavily overloaded. I have to create a constructor with dummy parameters in the CudaContext class, which is definitely not what a good fix should do.

To fix the issue, I think some changes on the design needs to be made. I think the author needs to know this problem, although the related functionality may not be commonly used.

It would be really great if you could fix the issue. But again, thanks for your work. It really makes my work a lot easier.

kunzmi commented 7 years ago

Hi,

Thanks for reporting! I also added an additional (internal) overload to the CudaContext constructors, which is then used by the PrimaryContext class. This fixes the issue that a normal context is always created, but you're right, the soution is not perfect... If I come up with a better way to fix this, I will change it, for now it is at least functional :)