Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rfc: Allow reading current context for another thread #842

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions api/lib/opentelemetry/context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ def create_key(name)
# Returns current context, which is never nil
#
# @return [Context]
def current
stack.last || ROOT
def current(thread = Thread.current)
# Avoid calling #stack directly so as to not have races in initializing the storage
thread[STACK_KEY]&.last || ROOT
end

# Associates a Context with the caller's current Fiber. Every call to
Expand Down
20 changes: 20 additions & 0 deletions api/test/opentelemetry/context_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -333,5 +333,25 @@
_(Context.current[bar_key]).must_be_nil
end
end

it 'allows accessing the current context for another thread' do
another_thread_context = Queue.new

another_thread = Thread.new do
ctx = Context.empty.set_value(foo_key, 'bar')
Context.with_current(ctx) do
another_thread_context << Context.current
sleep
end
end

ctx = another_thread_context.pop

_(Context.current(another_thread)).must_equal(ctx)
_(Context.current).wont_equal(ctx)

another_thread.kill
another_thread.join
end
end
end