Threads, Processes, IPC, and Synchronization |
Symbian C++ provides, for example the RSemaphore, RMutex, and RFastLock classes for synchronization. These classes have methods like Wait( ) and Signal() to lock and unlock the resource. If the locks are not handled properly, a deadlock may occur. An example of a deadlock is as given below. The example assumes that there are two threads in a process and there are two locks to protect two resources.
Thread 1 Thread 2 ======== ======== … … … … Lock A Lock B … … … … Lock B Lock A … … … … UnLock B UnLock A UnLock A UnLock B
Thus both threads will block indefinitely, leading to a deadlock.
There are many ways to avoid the deadlock by using the locks carefully. One of the easiest ways is to check the lock before blocking, and if the lock is open, then lock it; else return back instead of blocking. This operation has to be done atomically. Thus the operating system should provide a suitable API for this. At the moment, Symbian OS does not have any such API.
POSIX defines the following APIs that can be used to avoid such a situation:
With this API, the solution might look as follows:
Thread 1 Thread 2 ======= ======== … … … … Lock A Lock B … … … … begin1: begin2: TryLock B TryLock A If failed to Lock If failed to Lock then Unlock A then Unlock B sleep (10) sleep (10) Lock A Lock B Goto begin1: Goto begin2: … … … … UnLock B UnLock A UnLock A UnLock B
Similarly, there are two more useful APIs in POSIX:
There are no equivalent APIs for the above in Symbian OS.
©Nokia 2007 |