An Error: Using thrust::sort_by_key with OpenGL

I’m using sort_by_key in my OpenGL program. If I write:

int DrawGLScene(GLvoid)                         // Here's Where We Do All The Drawing
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);     // Clear The Screen And The Depth Buffer
    glLoadIdentity();                       // Reset The View
    
    thrust::sort_by_key(thrust::cuda::par.on(stream), dev_keys, dev_keys + N, dev_values);
}

And program will call DrawGLScene() circularly. The first time, sort_by_key is successful. But from second time, it will fail. Then I add a try:

try
{
thrust::sort_by_key(thrust::cuda::par.on(stream), dev_keys, dev_keys + 100, dev_values);
}
catch(thrust::system_error &e)
{
	cout << "Some other error happened during sort: " << e.what() << endl;
}

The error is : after cub_::DeviceRadixSort::SortPairs(1): invalid resource handle

I don’t know what it is.

But if I write code in InitGL():

int InitGL(GLvoid)                   
{
    thrust::sort_by_key(thrust::cuda::par.on(stream), dev_keys, dev_keys + N, dev_values);
}

or,

int InitGL(GLvoid)                   
{
    for(int i=0;i<100;i++)
    {
    thrust::sort_by_key(thrust::cuda::par.on(stream), dev_keys, dev_keys + N, dev_values);
    }
}

They are all OK.

I don’t know why it is. Can’t sort_by_key be used with OpenGL?