|
| 1 | +# Copyright 2019, OpenCensus Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from threading import Thread |
| 16 | +from opencensus.common.runtime_context import RuntimeContext |
| 17 | + |
| 18 | +RuntimeContext.register_slot('operation_id', '<empty>') |
| 19 | + |
| 20 | + |
| 21 | +def work(name): |
| 22 | + print('Entering worker:', RuntimeContext) |
| 23 | + RuntimeContext.operation_id = name |
| 24 | + print('Exiting worker:', RuntimeContext) |
| 25 | + |
| 26 | + |
| 27 | +if __name__ == '__main__': |
| 28 | + print('Main thread:', RuntimeContext) |
| 29 | + RuntimeContext.operation_id = 'main' |
| 30 | + |
| 31 | + print('Main thread:', RuntimeContext) |
| 32 | + |
| 33 | + # by default context is not propagated to worker thread |
| 34 | + thread = Thread(target=work, args=('foo',)) |
| 35 | + thread.start() |
| 36 | + thread.join() |
| 37 | + |
| 38 | + print('Main thread:', RuntimeContext) |
| 39 | + |
| 40 | + # user can propagate context explicitly |
| 41 | + thread = Thread( |
| 42 | + target=RuntimeContext.with_current_context(work), |
| 43 | + args=('bar',), |
| 44 | + ) |
| 45 | + thread.start() |
| 46 | + thread.join() |
| 47 | + |
| 48 | + print('Main thread:', RuntimeContext) |
0 commit comments