4

我正在尝试向锁类添加一个新插槽。这很有用,因为我在层次结构中有很多锁,如果我为每个锁存储父锁,则在调试时更容易检测问题。

不幸的是,这显然不能用 ensure-class 函数来完成。我可以将插槽添加到“进程”,但不能添加到“锁定”,因为它被列为内置类。请参阅我之前的问题,了解如何为“进程: lisp,CLOS:向进程类添加插槽”

你知道如何解决这个问题吗?如果不可能,我能想到的唯一选择是将锁的层次关系存储在哈希表中,但是由于某些锁是在运行时和不同进程中创建的,所以我必须再添加一个锁访问在锁上存储元数据的哈希表。

这让我觉得效率非常低。你有更好的主意吗?

编辑:为澄清起见,我使用的是 Clozure Common Lisp。

4

2 回答 2

3

您可以使用:metaclassdefclass 形式的 class 选项指定元类。

CL-USER> (defclass hierarchical-lock (lock)
           ((parent :initarg :parent :reader parent))
           (:metaclass built-in-class))
#<BUILT-IN-CLASS HIERARCHICAL-LOCK>

但是,即使您可以这样做并获得课程,我也不确定您将如何实例化它。尝试使用make-instance失败:

CL-USER> (make-instance 'hierarchical-lock)

; There is no applicable method for the generic function:
;   #<STANDARD-GENERIC-FUNCTION MAKE-INSTANCE #x30200002676F>
; when called with arguments:
;   (#<BUILT-IN-CLASS HIERARCHICAL-LOCK>)
;    [Condition of type SIMPLE-ERROR]

make-lockl0-aprims.lisp中实现为

(defun make-lock (&optional name)
  "Create and return a lock object, which can be used for synchronization
between threads."
  (%make-lock (%make-recursive-lock-ptr) name))

You can keep following the implementation of %make-lock until you get to the low level implementation details, but it's clear that locks are not obtained the same way that typical CLOS instances are.

In addition to Rainer Joswig's suggestion in a comment on this answer that you let the CCL developers know that you would appreciate locks being CLOS objects, you can always use some aggregation and define your own hierarchical-lock that has slot for its primitive lock and a slot for parent. By the magic of generic functions, you can implement methods on the generic functions that work with locks so that your hierarchical-lock behaves like a built in lock. (This presumes that the lock API is defined in terms of generic functions.)

于 2013-06-15T19:49:41.003 回答
0

您可以使用具有这样一个插槽的子类。

(defclass hierarchical-lock (lock)
  ((parent :initarg :parent :reader parent)))
于 2013-06-15T18:11:31.820 回答