88 */
99
1010#include <stddef.h>
11+ #include <stdint.h>
1112#include <string.h>
1213
1314#include "base_alloc_global.h"
1920#include "provider_level_zero_internal.h"
2021#include "provider_tracking.h"
2122#include "utils_common.h"
23+ #include "utils_concurrency.h"
2224#include "utils_log.h"
2325#if !defined(UMF_NO_HWLOC )
2426#include "topology.h"
@@ -34,35 +36,46 @@ static umf_ctl_node_t CTL_NODE(umf)[] = {CTL_CHILD(provider), CTL_CHILD(pool),
3436void initialize_global_ctl (void ) { CTL_REGISTER_MODULE (NULL , umf ); }
3537
3638int umfInit (void ) {
37- if (utils_fetch_and_add_u64 (& umfRefCount , 1 ) == 0 ) {
38- utils_log_init ();
39- TRACKER = umfMemoryTrackerCreate ();
40- if (!TRACKER ) {
41- LOG_ERR ("Failed to create memory tracker" );
42- return -1 ;
39+ uint64_t refCount ;
40+ do {
41+ if (utils_fetch_and_add_u64 (& umfRefCount , 1 ) == 0 ) {
42+ utils_log_init ();
43+ TRACKER = umfMemoryTrackerCreate ();
44+ if (!TRACKER ) {
45+ LOG_ERR ("Failed to create memory tracker" );
46+ utils_atomic_decrement_size_t (& umfRefCount );
47+ return -1 ;
48+ }
49+
50+ LOG_DEBUG ("UMF tracker created" );
51+
52+ umf_result_t umf_result = umfIpcCacheGlobalInit ();
53+ if (umf_result != UMF_RESULT_SUCCESS ) {
54+ LOG_ERR ("Failed to initialize IPC cache" );
55+ umfMemoryTrackerDestroy (TRACKER );
56+ utils_atomic_decrement_size_t (& umfRefCount );
57+ return -1 ;
58+ }
59+
60+ LOG_DEBUG ("UMF IPC cache initialized" );
61+ initialize_global_ctl ();
62+
63+ utils_atomic_increment_size_t (& umfRefCount );
4364 }
4465
45- LOG_DEBUG ("UMF tracker created" );
66+ do {
67+ utils_atomic_load_acquire_u64 (& umfRefCount , & refCount );
68+ } while (refCount == 1 );
4669
47- umf_result_t umf_result = umfIpcCacheGlobalInit ();
48- if (umf_result != UMF_RESULT_SUCCESS ) {
49- LOG_ERR ("Failed to initialize IPC cache" );
50- return -1 ;
51- }
52-
53- LOG_DEBUG ("UMF IPC cache initialized" );
54- initialize_global_ctl ();
55- }
70+ } while (refCount > 2 );
5671
57- if (TRACKER ) {
58- LOG_DEBUG ("UMF library initialized" );
59- }
72+ LOG_DEBUG ("UMF library initialized" );
6073
6174 return 0 ;
6275}
6376
6477void umfTearDown (void ) {
65- if (utils_fetch_and_sub_u64 (& umfRefCount , 1 ) == 1 ) {
78+ if (utils_fetch_and_sub_u64 (& umfRefCount , 1 ) == 2 ) {
6679#if !defined(_WIN32 ) && !defined(UMF_NO_HWLOC )
6780 umfMemspaceHostAllDestroy ();
6881 umfMemspaceHighestCapacityDestroy ();
@@ -94,6 +107,7 @@ void umfTearDown(void) {
94107 fini_cu_global_state ();
95108 fini_tbb_global_state ();
96109 LOG_DEBUG ("UMF library finalized" );
110+ utils_atomic_decrement_size_t (& umfRefCount );
97111 }
98112}
99113
0 commit comments