Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing external resources (similar to RAII in C++?)

In common lisp, what is the preferred way to manage external resources (sockets, filesystem handles, etc)?

I'm trying to make a simple opengl 2d platformer in common lisp. The problem is I'm not quite sure how to track OpenGL textures (must be deleted with glDeleteTextures when they are no longer needed).

In C++ I preferred to use following scheme:

  1. Make texture class
  2. Make smart/weak pointers for that texture class
  3. Store textures in map (dictionary/hashtable) that maps file names to weak pointers to textures.
  4. When new textures are requested, look into map, and see if there's a non-null (nil) weak pointer available. If it is available, return existing object, otherwise load new texture.

However, I'm not quite sure how to port this scheme to common lisp, because:

  1. There are no destructors.
  2. There's garbage collector, and it seems my implementation (clozureCL on windows platform) supports finalizers, but as far as I can tell it is not recommended to use finalizers in common lisp because they're not deterministic.
  3. The preferred way of managing resources using (with-* doesn't look suitable there, because resources can be shared, and loaded/unloaded in the middle of function call.

As far as I can tell, there are several approaches available:

  1. Give up on automatic resource managment, and do it manually.
  2. Implement something similar to C++ RAII, weakpointer and smartpointer using macros (this code probably doesn't work):

    (defclass destructible () ())
    
    (defmethod destroy ((obj destructible)) (print (format nil "destroy: ~A" obj)))
    
    (defparameter *destructible-classes-list* nil)
    
    (defmethod initialize-instance :after ((obj destructible) &key)
      (progn
          (push *destructible-classes-list* obj)
          (print (format nil "init-instance: ~A" obj))))
    
    (defmacro with-cleanup (&rest body)
      `(let ((*destructible-classes-list* nil))
        (progn ,@body (mapcar (lambda (x) (destroy x)) *destructible-classes-list*))))
    
    (defclass refdata (destructible)
      ((value :accessor refdata-value :initform nil)
       (ref :accessor refdata-ref :initform 0)
       (weakrefcount :accessor refdata-weakref :initform 0)))
    
    (defmethod incref ((ref refdata))
      (if ref (incf (refdata-ref ref))))
    
    (defmethod decref ((ref refdata))
      (if ref
        (progn (decf (refdata-ref ref))
         (if (<= (refdata-ref ref) 0) 
           (progn (destroy (refdata-value ref))
              (setf (refdata-value ref) nil))))))
    
    (defmethod incweakref ((ref refdata))
      (if ref (incf (refdata-weakref ref))))
    
    (defmethod decweakref ((ref refdata))
      (if ref (decf (refdata-weakref ref))))
    
    (defclass refbase (destructible) ((data :accessor refbase-data :initform nil)))
    
    (defmethod deref ((ref refbase))
      (if (and (refbase-data ref) (refdata-value (refbase-data ref)))
        (refdata-value (refbase-data ref))
        nil))
    
    (defclass strongref (refbase) ())
    
    (defclass weakref (refbase) ())
    
    (defmethod destroy :before ((obj strongref))
      (decref (refbase-data obj)))
    
    (defmethod destroy :before ((obj weakref))
      (decweakref (refbase-data obj)))
    
    (defmethod initialize-instance :after ((obj strongref) &key)
      (incref (refbase-data obj)))
    
    (defmethod initialize-instance :after ((obj weakref) &key)
      (incweakref (refbase-data obj)))
    

Is there a better way to do it?

C++ Concepts Explanation: What is a smart pointer and when should I use one?

like image 233
SigTerm Avatar asked Nov 10 '12 14:11

SigTerm


People also ask

Does C have RAII?

> C does not have RAII-like memory management in any way. C does not have memory management in any way period. The C standard library does. How you get to something with dynamic scoping like RAII in C is to use a different library for managing memory.

What is RAII in programming?

Resource Acquisition Is Initialization or RAII, is a C++ programming technique which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the ...

What is RAII and why is it important?

RAII is an important C++ idiom for resource management. Notably, RAII provides a structural idiom for proper resource management with exceptions. The power of the idiom is in the guarantees it provides. Properly used, the destructor for your RAII-object is guaranteed to be called to allow you to free resources.

What is resource management in C++?

Resource management frees the client from having to worry about the lifetime of the managed object, eliminating memory leaks and other problems in C++ code. A resource could be any object that required dynamic creation/deletion – memory, files, sockets, mutexes, etc.


1 Answers

If you want to handle a dynamic extent scope use UNWIND-PROTECT. If the program leaves that scope - normally or on error - the clean-up form is called. Just deallocate there or do whatever you want.

Sometimes Lisps use some kind of 'resource' mechanism to keep track of used and unused objects. Such a library provides fast allocation from a pool, allocating, initialization, deallocation, mapping of resourced object. CLIM defines a primitive version: Resources. CCL has a similar primitive version of it.

In a Lisp with 'timers', you can run a function periodically which looks for 'objects' to deallocate. In CCL you can use a thread which sleeps for a certain time using PROCESS-WAIT.

A bit about your coding style:

  • FORMAT can directly output to a stream, no PRINT needed
  • (defmethod foo ((e bar)) (if e ...)) : the IF makes no sense. e will always be an object.
  • many PROGN are not needed. Where needed, it could be removed when IF is replaced by WHEN.
like image 184
Rainer Joswig Avatar answered Oct 22 '22 22:10

Rainer Joswig