Posts

Showing posts with the label Lock

Locking Guidelines

In my last post ( Lock Up Unlocked ), I gave you some basic guidelines for locking resources in multi-threaded programs. Basic guidelines for locking. Avoid simultaneously locking multiple shared resources in a single thread. If multiple shared resources must be locked simultaneously, endeavor that all threads lock the resources in the same order and unlock them in reverse order. If they can't be unlocked in reverse order, then endeavor to unlock in the same order and do not lock an earlier resource till all later locks are released. If you can't follow these guidelines, then timeout. In today's post, I am going to elaborate a little on each principle. But first, let's discuss "resources". Many of you can quickly name the commonly understood resources. Things like memory, cpu, network jump right out, but that's because we are so used to looking at Task Manager and Resource Monitor. Besides, they are a little esoteric, programmers are concerned about sp...

Lock Up Unlocked

In my last post ( Locked Up! ), I gave an example of a simple deadlocking application. If you run it and click the button a few times rapidly, the application stops responding. Then, if you pause the program and examine the stack trace of each thread, you find the GUI thread waiting for the lock, and the child thread waiting for Invoke() to return. The child thread is holding the lock, so the application is deadlocked. This is also known as a "deadly embrace". So, I affectionately referred to the two resources as Resource RA and Resource RB and asked you to identify them in the program. One of the resources is pretty obvious. That would be the lblResult.Text . It doesn't matter whether you call this RA or RB, so I'll call it Resource RA. Regardless, for some odd reason, the programmer has decided that the lblResult.Text property needs to be protected from simultaneous read and write. This protection is not really necessary, but pretend for a moment a valid s...

Locked Up!

Today's example is NOT useful code. Instead, it's a simple example of a bad practice in multi-threaded code floating around out there in programming land. This example is C# specific, but the concepts apply to other languages as well. Since this is a bad example, I'll start off by telling you why its bad. The application locks then blocks on another resource. It's as simple as that. Many of you understand that if Thread A locks Resource RA and tries to lock Resource RB, while Thread B locks Resource RB and then tries to lock Resource RA, you have a classic "deadlock". The following code "deadlocks". Run it and click the button a few times and it will deadlock. So, the real question is not "why is it deadlocking?" I just told you up front, it's a classic deadlock. The real question is "what are the equivalents in this program of Resources RA and RB?" To answer this question, you can run the program in your favorite de...