Class: DatadogThreadTracer::ThreadTracer

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog_thread_tracer/thread_tracer.rb

Overview

trace within threads

Instance Method Summary collapse

Constructor Details

#initializeThreadTracer

Returns a new instance of ThreadTracer.



6
7
8
9
# File 'lib/datadog_thread_tracer/thread_tracer.rb', line 6

def initialize
  @threads = []
  @thread_count = 0
end

Instance Method Details

#join_threadsObject



55
56
57
# File 'lib/datadog_thread_tracer/thread_tracer.rb', line 55

def join_threads
  @threads.each(&:join)
end

#trace(trace_name: nil, thread_args: []) { ... } ⇒ Object

Examples:

Pass trace_name

DatadogThreadTracer.trace do |t|
  t.trace(trace_name: "trace_name") do
    # do something. (this block is called in thread)
  end
end

Pass single arg to Thread

DatadogThreadTracer.trace do |t|
  t.trace(thread_args: 1) do |a|
    a
    #=> 1
  end
end

Pass multiple args to Thread

DatadogThreadTracer.trace do |t|
  t.trace(thread_args: [2, 3]) do |a, b|
    a + b
    #=> 5
  end
end

Parameters:

  • trace_name (String) (defaults to: nil)
  • thread_args (Array, Object) (defaults to: [])

    Passed to Thread.start

Yields:

  • Processes you want to execute in a thread



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/datadog_thread_tracer/thread_tracer.rb', line 38

def trace(trace_name: nil, thread_args: [])
  @thread_count += 1
  trace_name ||= "thread_#{@thread_count}"

  tracer = Datadog::Tracing.send(:tracer)

  @threads << Thread.start(trace_name, tracer.provider.context, Array(thread_args)) do |name, context, args|
    tracer = Datadog::Tracing.send(:tracer)

    # c.f. https://github.com/DataDog/dd-trace-rb/issues/1460
    tracer.provider.context = context
    Datadog::Tracing.trace(name) do
      yield(*args)
    end
  end
end