@@ -29,8 +29,8 @@ class RubyThreadLocalVar < AbstractThreadLocalVar
29
29
# array, so we don't leak memory
30
30
31
31
# @!visibility private
32
- FREE = [ ]
33
- LOCK = Mutex . new
32
+ FREE = [ ]
33
+ LOCK = Mutex . new
34
34
ARRAYS = { } # used as a hash set
35
35
@@next = 0
36
36
private_constant :FREE , :LOCK , :ARRAYS
@@ -72,9 +72,9 @@ def value=(value)
72
72
def allocate_storage
73
73
@index = LOCK . synchronize do
74
74
FREE . pop || begin
75
- result = @@next
76
- @@next += 1
77
- result
75
+ result = @@next
76
+ @@next += 1
77
+ result
78
78
end
79
79
end
80
80
ObjectSpace . define_finalizer ( self , self . class . threadlocal_finalizer ( @index ) )
@@ -83,13 +83,15 @@ def allocate_storage
83
83
# @!visibility private
84
84
def self . threadlocal_finalizer ( index )
85
85
proc do
86
- LOCK . synchronize do
87
- FREE . push ( index )
88
- # The cost of GC'ing a TLV is linear in the number of threads using TLVs
89
- # But that is natural! More threads means more storage is used per TLV
90
- # So naturally more CPU time is required to free more storage
91
- ARRAYS . each_value do |array |
92
- array [ index ] = nil
86
+ Thread . new do # avoid error: can't be called from trap context
87
+ LOCK . synchronize do
88
+ FREE . push ( index )
89
+ # The cost of GC'ing a TLV is linear in the number of threads using TLVs
90
+ # But that is natural! More threads means more storage is used per TLV
91
+ # So naturally more CPU time is required to free more storage
92
+ ARRAYS . each_value do |array |
93
+ array [ index ] = nil
94
+ end
93
95
end
94
96
end
95
97
end
@@ -98,10 +100,12 @@ def self.threadlocal_finalizer(index)
98
100
# @!visibility private
99
101
def self . thread_finalizer ( array )
100
102
proc do
101
- LOCK . synchronize do
102
- # The thread which used this thread-local array is now gone
103
- # So don't hold onto a reference to the array (thus blocking GC)
104
- ARRAYS . delete ( array . object_id )
103
+ Thread . new do # avoid error: can't be called from trap context
104
+ LOCK . synchronize do
105
+ # The thread which used this thread-local array is now gone
106
+ # So don't hold onto a reference to the array (thus blocking GC)
107
+ ARRAYS . delete ( array . object_id )
108
+ end
105
109
end
106
110
end
107
111
end
0 commit comments