@@ -83,6 +83,10 @@ impl Environment {
8383
8484 #[ tracing:: instrument]
8585 fn new ( name : String , log_level : LoggingLevel ) -> Result < Environment > {
86+ // NOTE: Because 'G_ENV' is a lazy_static, locking it will, initially, create
87+ // a new Arc<Mutex<EnvironmentSingleton>> with a strong count of 1.
88+ // Cloning it to embed it inside the 'Environment' to return
89+ // will thus increase the strong count to 2.
8690 let mut environment_guard = G_ENV
8791 . lock ( )
8892 . expect ( "Failed to acquire lock: another thread panicked?" ) ;
@@ -121,13 +125,24 @@ impl Environment {
121125 * g_env_ptr = env_ptr;
122126 environment_guard. name = name;
123127
128+ // NOTE: Cloning the lazy_static 'G_ENV' will increase its strong count by one.
129+ // If this 'Environment' is the only one in the process, the strong count
130+ // will be 2:
131+ // * one lazy_static 'G_ENV'
132+ // * one inside the 'Environment' returned
124133 Ok ( Environment { env : G_ENV . clone ( ) } )
125134 } else {
126135 warn ! (
127136 name = environment_guard. name. as_str( ) ,
128137 env_ptr = format!( "{:?}" , environment_guard. env_ptr) . as_str( ) ,
129138 "Environment already initialized, reusing it." ,
130139 ) ;
140+
141+ // NOTE: Cloning the lazy_static 'G_ENV' will increase its strong count by one.
142+ // If this 'Environment' is the only one in the process, the strong count
143+ // will be 2:
144+ // * one lazy_static 'G_ENV'
145+ // * one inside the 'Environment' returned
131146 Ok ( Environment { env : G_ENV . clone ( ) } )
132147 }
133148 }
@@ -152,6 +167,11 @@ impl Drop for Environment {
152167 . lock ( )
153168 . expect ( "Failed to acquire lock: another thread panicked?" ) ;
154169
170+ // NOTE: If we drop an 'Environment' we (obviously) have _at least_
171+ // one 'G_ENV' strong count (the one in the 'env' member).
172+ // There is also the "original" 'G_ENV' which is a the lazy_static global.
173+ // If there is no other environment, the strong count should be two and we
174+ // can properly free the sys::OrtEnv pointer.
155175 if Arc :: strong_count ( & G_ENV ) == 2 {
156176 let release_env = g_ort ( ) . ReleaseEnv . unwrap ( ) ;
157177 let env_ptr: * mut sys:: OrtEnv = * environment_guard. env_ptr . get_mut ( ) ;
0 commit comments