@@ -63,8 +63,20 @@ static PyStructSequence_Desc struct_rusage_desc = {
6363 16 /* n_in_sequence */
6464};
6565
66- static int initialized ;
67- static PyTypeObject StructRUsageType ;
66+ typedef struct {
67+ PyTypeObject * StructRUsageType ;
68+ } resourcemodulestate ;
69+
70+
71+ static inline resourcemodulestate *
72+ get_resource_state (PyObject * module )
73+ {
74+ void * state = PyModule_GetState (module );
75+ assert (state != NULL );
76+ return (resourcemodulestate * )state ;
77+ }
78+
79+ static struct PyModuleDef resourcemodule ;
6880
6981/*[clinic input]
7082resource.getrusage
@@ -91,7 +103,8 @@ resource_getrusage_impl(PyObject *module, int who)
91103 return NULL ;
92104 }
93105
94- result = PyStructSequence_New (& StructRUsageType );
106+ result = PyStructSequence_New (
107+ get_resource_state (module )-> StructRUsageType );
95108 if (!result )
96109 return NULL ;
97110
@@ -336,10 +349,10 @@ resource_methods[] = {
336349
337350/* Module initialization */
338351
339-
340352static int
341353resource_exec (PyObject * module )
342354{
355+ resourcemodulestate * state = get_resource_state (module );
343356#define ADD_INT (module , value ) \
344357 do { \
345358 if (PyModule_AddIntConstant(module, #value, value) < 0) { \
@@ -353,13 +366,12 @@ resource_exec(PyObject *module)
353366 Py_DECREF (PyExc_OSError );
354367 return -1 ;
355368 }
356- if (!initialized ) {
357- if (PyStructSequence_InitType2 (& StructRUsageType ,
358- & struct_rusage_desc ) < 0 )
359- return -1 ;
360- }
361369
362- if (PyModule_AddType (module , & StructRUsageType ) < 0 ) {
370+ state -> StructRUsageType = PyStructSequence_NewType (& struct_rusage_desc );
371+ if (state -> StructRUsageType == NULL ) {
372+ return -1 ;
373+ }
374+ if (PyModule_AddType (module , state -> StructRUsageType ) < 0 ) {
363375 return -1 ;
364376 }
365377
@@ -483,8 +495,6 @@ resource_exec(PyObject *module)
483495 Py_DECREF (v );
484496 return -1 ;
485497 }
486-
487- initialized = 1 ;
488498 return 0 ;
489499
490500#undef ADD_INT
@@ -495,12 +505,32 @@ static struct PyModuleDef_Slot resource_slots[] = {
495505 {0 , NULL }
496506};
497507
508+ static int
509+ resourcemodule_traverse (PyObject * m , visitproc visit , void * arg ) {
510+ Py_VISIT (get_resource_state (m )-> StructRUsageType );
511+ return 0 ;
512+ }
513+
514+ static int
515+ resourcemodule_clear (PyObject * m ) {
516+ Py_CLEAR (get_resource_state (m )-> StructRUsageType );
517+ return 0 ;
518+ }
519+
520+ static void
521+ resourcemodule_free (void * m ) {
522+ resourcemodule_clear ((PyObject * )m );
523+ }
524+
498525static struct PyModuleDef resourcemodule = {
499526 PyModuleDef_HEAD_INIT ,
500527 .m_name = "resource" ,
501- .m_size = 0 ,
528+ .m_size = sizeof ( resourcemodulestate ) ,
502529 .m_methods = resource_methods ,
503530 .m_slots = resource_slots ,
531+ .m_traverse = resourcemodule_traverse ,
532+ .m_clear = resourcemodule_clear ,
533+ .m_free = resourcemodule_free ,
504534};
505535
506536PyMODINIT_FUNC
0 commit comments