2121#include <reflect/reflect_function.h>
2222#include <reflect/reflect_value_type.h>
2323
24+ #include <threading/threading_atomic_ref_count.h>
25+
2426#include <reflect/reflect_memory_tracker.h>
2527
2628#include <log/log.h>
@@ -34,7 +36,7 @@ struct function_type
3436 signature s ;
3537 function_impl impl ;
3638 function_interface interface ;
37- size_t ref_count ;
39+ struct threading_atomic_ref_count_type ref ;
3840 enum async_id async ;
3941 void * data ;
4042};
@@ -77,7 +79,6 @@ function function_create(const char *name, size_t args_count, function_impl impl
7779 }
7880
7981 func -> impl = impl ;
80- func -> ref_count = 0 ;
8182 func -> async = SYNCHRONOUS ;
8283 func -> data = NULL ;
8384
@@ -87,12 +88,11 @@ function function_create(const char *name, size_t args_count, function_impl impl
8788 {
8889 log_write ("metacall" , LOG_LEVEL_ERROR , "Invalid function signature allocation" );
8990
90- free (func -> name );
91- free (func );
92-
93- return NULL ;
91+ goto function_create_error ;
9492 }
9593
94+ threading_atomic_ref_count_store (& func -> ref , 0 );
95+
9696 func -> interface = singleton ? singleton () : NULL ;
9797
9898 if (func -> interface != NULL && func -> interface -> create != NULL )
@@ -101,16 +101,19 @@ function function_create(const char *name, size_t args_count, function_impl impl
101101 {
102102 log_write ("metacall" , LOG_LEVEL_ERROR , "Invalid function (%s) create callback <%p>" , func -> name , func -> interface -> create );
103103
104- free (func -> name );
105- free (func );
106-
107- return NULL ;
104+ goto function_create_error ;
108105 }
109106 }
110107
111108 reflect_memory_tracker_allocation (function_stats );
112109
113110 return func ;
111+
112+ function_create_error :
113+ free (func -> name );
114+ free (func );
115+
116+ return NULL ;
114117}
115118
116119int function_increment_reference (function func )
@@ -120,12 +123,11 @@ int function_increment_reference(function func)
120123 return 1 ;
121124 }
122125
123- if (func -> ref_count == SIZE_MAX )
126+ if (threading_atomic_ref_count_increment ( & func -> ref ) == 1 )
124127 {
125128 return 1 ;
126129 }
127130
128- ++ func -> ref_count ;
129131 reflect_memory_tracker_increment (function_stats );
130132
131133 return 0 ;
@@ -138,12 +140,11 @@ int function_decrement_reference(function func)
138140 return 1 ;
139141 }
140142
141- if (func -> ref_count == 0 )
143+ if (threading_atomic_ref_count_decrement ( & func -> ref ) == 1 )
142144 {
143145 return 1 ;
144146 }
145147
146- -- func -> ref_count ;
147148 reflect_memory_tracker_decrement (function_stats );
148149
149150 return 0 ;
@@ -639,7 +640,7 @@ void function_destroy(function func)
639640 log_write ("metacall" , LOG_LEVEL_ERROR , "Invalid reference counter in function: %s" , func -> name ? func -> name : "<anonymous>" );
640641 }
641642
642- if (func -> ref_count == 0 )
643+ if (threading_atomic_ref_count_load ( & func -> ref ) == 0 )
643644 {
644645 if (func -> name == NULL )
645646 {
0 commit comments