Resource Creation and Destruction: lock and unLock
Because the creation of graphic resources is generally memory intensive on most graphic systems, Views implements a caching mechanism to minimize graphic resource allocation.
Resource objects are maintained by the IlvDisplay instances of your application. They should normally not be created and destroyed using the operators new and delete. Instead, Views provides the following member functions:
-
IlvDisplay methods getXXX, where XXX stands for a resource class name without the Ilv prefix (for instance, getColor, getFont, and so on).
-
Methods IlvResource::lock and IlvResource::unLock respectively increment and decrement the internal reference count of the resource. When this count reaches zero, the resource is deleted.
Locking and Unlocking Procedures
Graphic resources should be used in the following manner:
-
Request your IlvDisplay instance to allocate a resource for you. If this resource already exists in the system (for instance, the color you query for is already in use in a palette somewhere), no further allocation is done, and the existing resource is returned.
-
Inform Views that this resource must be kept safe by calling IlvResource::lock, then use that resource.
-
Use IlvResource::unLock to let Views know that you have finished using the resource.
Resource management is closely concerned with the ways in which you lock and unlock your resources. Whenever you need a specific resource in one of your persistent objects, you should use this mechanism to make sure that it will stay safe within your IlvDisplay instance. If your application needs more than one instance of IlvDisplay, you have to create resources within each environment, since resources cannot be shared between the different IlvDisplay contexts.
During the lifetime of a resource, the number of calls to IlvResource::lock must exactly match the number of calls to IlvResource::unLock. If there are more calls to lock, the resource remains allocated even if it is no longer in use, and therefore limits your application’s requirements. If there are more calls to unlock, the application may crash because of a memory error.
Rules for Locking and Unlocking
You should follow these rules for locking and unlocking graphic resources:
-
Once you get a resource, lock it, use it, and unlock it when you are done.
-
You should not unlock a resource that you have not locked yourself, unless you are sure that your operation is correct.
-
You should never use a resource after you have unlocked it, just like you should never use a pointer after you have freed it; IlvResource::unLock potentially means delete.
-
There are times when you do not need to lock and unlock a resource. For instance, if you get the foreground color of an object and pass it to another object that will lock it. In such cases, locking and unlocking the resource is not necessary, but it does no damage either.