lib/gvl-tracing.rb in gvl-tracing-1.4.0 vs lib/gvl-tracing.rb in gvl-tracing-1.5.0

- old
+ new

@@ -34,56 +34,64 @@ private :_start private :_stop def start(file) _start(file) + _init_local_storage(Thread.list) @path = file return unless block_given? begin yield ensure - _stop + stop end end def stop - thread_list = Thread.list + thread_list = _stop - _stop - append_thread_names(thread_list) + + trim_all_seen_threads end private def append_thread_names(list) - threads_name = aggreate_thread_list(list).join(",\n") - File.open(@path, 'a') do |f| - f.puts(threads_name) + thread_names = aggreate_thread_list(list).join(",\n") + File.open(@path, "a") do |f| + f.puts(thread_names) f.puts("]") end end def aggreate_thread_list(list) list.each_with_object([]) do |t, acc| next unless t.name || t == Thread.main - acc << " {\"ph\": \"M\", \"pid\": #{Process.pid}, \"tid\": #{t.native_thread_id}, \"name\": \"thread_name\", \"args\": {\"name\": \"#{thread_label(t)}\"}}" + acc << " {\"ph\": \"M\", \"pid\": #{Process.pid}, \"tid\": #{thread_id_for(t)}, \"name\": \"thread_name\", \"args\": {\"name\": \"#{thread_label(t)}\"}}" end end REGEX = /lib(?!.*lib)\/([a-zA-Z-]+)/ def thread_label(thread) if thread == Thread.main - return thread.name ? thread.name : "Main Thread" + return thread.name || "Main Thread" end lib_name = thread.to_s.match(REGEX) return thread.name if lib_name.nil? "#{thread.name} from #{lib_name[1]}" end + + def thread_id_for(t) + RUBY_VERSION.start_with?("3.2.") ? t.native_thread_id : _thread_id_for(t) + end end end + +# Eagerly initialize context for main thread +GvlTracing.send(:thread_id_for, Thread.main)