Don’t constantly try to aquire locks on idle events of GUI frameworks. You can try to aquire locks on idle events here and there, i.e. on some idle events, just don’t do it on every single idle event.

As you may know, this is basically what a GUI framework’s main loop looks like:

while <there is an event to handle in the event queue>
    handle the event

As your application is being played around with by the user, events (like mouse move events, mouse click events, keyboard press events, etc) go into your application’s event queue. This service is offered by the operating system. The operating system knows all the windows assocaited for a particular process, and as the user uses his/her mouse/keyboard to play with the window of a particular process, the OS puts all those events in the event queue it created for that process.

If the user is not playing with your window for a little while, there will be nothing in the event queue. This time is termed “idle” time, because the main loop of the application has no events to handle.

GUI frameworks (as well as some other frameworks like game engines) offer you the ability to run some of your code during this idle time.

Be sure to keep your idle time callbacks to short executing functions, otherwise you will make the application “unresponsive”. This is because while your long callback is executing, the application is not handling any events that are put into its queue, so as the user is moving the mouse to say resize your window, all those events are going into the queue, but your application’s main thread is still running code in your idle time callback function, thus it does nothing in response to the user trying to resize your window.

I recently ran into this when I was trying to aquire a lock on every single idle event. So basically my thought process was “ok as long as the application has nothing to do, let me try to aquire this lock”. Aquiring a lock is an expensive operation, especially if another thread is constantly aquiring that lock, because you then have to wait for the other thread to release it, and while you are waiting, you are blocked!

This basically led to my application being very unresponsive, see:

Here is what it looked like after I changed it to aquire a lock only on some idle events (about every second):