You can (?) determine whether a CUDA context is the primary one by calling cuDevicePrimaryCtxRetain()
and comparing the returned pointer to the context you have. But - what if nobody's created the primary context yet? Is there a cheaper way to obtain the negative answer then? Or - is it impossible for a non-primary context to exist while the primary does not?
Asked
Active
Viewed 380 times
2

einpoklum
- 118,144
- 57
- 340
- 684
1 Answers
1
You can check whether the primary context has been created ("activated") or not:
inline bool primary_context_is_active(int device_id)
{
unsigned flags;
int is_active;
CUresult status = cuDevicePrimaryCtxGetState(device_id, &flags, &is_active);
if (status != CUDA_SUCCESS) { /* error handling here */ }
return is_active;
}
Now, if the primary context is not active, then you know your context is not the primary one; if it is active, you can use cuDevicePrimaryCtxRetain()
, and - unless you're doing something multi-threaded or using coroutines etc. - you know it'll be a cheap call.
This of course depends on assuming your context is not an invalid primary context handle after disactivation.

einpoklum
- 118,144
- 57
- 340
- 684
-
@talonmies: Oh, yes, you're right, it's the primary context. – einpoklum Aug 09 '22 at 13:17