+/* ... Check if the module is loaded ....................................... */
+
+static I32 a_loaded = 0;
+
+#if A_THREADSAFE
+
+#define PTABLE_NAME ptable_loaded
+#define PTABLE_NEED_DELETE 1
+#define PTABLE_NEED_WALK 0
+
+#include "ptable.h"
+
+#define ptable_loaded_store(T, K, V) ptable_loaded_store(aPTBLMS_ (T), (K), (V))
+#define ptable_loaded_delete(T, K) ptable_loaded_delete(aPTBLMS_ (T), (K))
+#define ptable_loaded_free(T) ptable_loaded_free(aPTBLMS_ (T))
+
+static ptable *a_loaded_cxts = NULL;
+
+static int a_is_loaded(pTHX_ void *cxt) {
+#define a_is_loaded(C) a_is_loaded(aTHX_ (C))
+ int res = 0;
+
+ A_LOADED_LOCK;
+ if (a_loaded_cxts && ptable_fetch(a_loaded_cxts, cxt))
+ res = 1;
+ A_LOADED_UNLOCK;
+
+ return res;
+}
+
+static int a_set_loaded_locked(pTHX_ void *cxt) {
+#define a_set_loaded_locked(C) a_set_loaded_locked(aTHX_ (C))
+ int global_setup = 0;
+
+ if (a_loaded <= 0) {
+ assert(a_loaded == 0);
+ assert(!a_loaded_cxts);
+ a_loaded_cxts = ptable_new();
+ global_setup = 1;
+ }
+ ++a_loaded;
+ assert(a_loaded_cxts);
+ ptable_loaded_store(a_loaded_cxts, cxt, cxt);
+
+ return global_setup;
+}
+
+static int a_clear_loaded_locked(pTHX_ void *cxt) {
+#define a_clear_loaded_locked(C) a_clear_loaded_locked(aTHX_ (C))
+ int global_teardown = 0;
+
+ if (a_loaded > 1) {
+ assert(a_loaded_cxts);
+ ptable_loaded_delete(a_loaded_cxts, cxt);
+ --a_loaded;
+ } else if (a_loaded_cxts) {
+ assert(a_loaded == 1);
+ ptable_loaded_free(a_loaded_cxts);
+ a_loaded_cxts = NULL;
+ a_loaded = 0;
+ global_teardown = 1;
+ }
+
+ return global_teardown;
+}
+
+#else
+
+#define a_is_loaded(C) (a_loaded > 0)
+#define a_set_loaded_locked(C) ((a_loaded++ <= 0) ? 1 : 0)
+#define a_clear_loaded_locked(C) ((--a_loaded <= 0) ? 1 : 0)
+
+#endif
+