How can I determine whether a CUDA context is the primary one - cheaply?

553 views Asked by At

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?

1

There are 1 answers

5
einpoklum On

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.