OpenCensus运行时上下文
opencensus-context的Python项目详细描述
opencensus运行时上下文提供进程内上下文传播。 默认情况下,thread local storage用于python 2.7、3.4和3.5; contextvars用于python>;=3.6,它提供asyncio支持。
安装
此库默认使用opencensus安装,不需要 显式安装。
用法
在大多数情况下,上下文传播自动发生在进程中, 遵循线程和异步协程的控制流。运行时 上下文是存储在context variable中的字典 如果可用,并且在thread local storage 否则。
在某些情况下,您可能需要显式地传播上下文:
显式线程创建
fromthreadingimportThreadfromopencensus.common.runtime_contextimportRuntimeContextdefwork(name):# here you will get the context from the parent threadprint(RuntimeContext)thread=Thread(# propagate context explicitlytarget=RuntimeContext.with_current_context(work),args=('foobar',),)thread.start()thread.join()
线程池
frommultiprocessing.dummyimportPoolasThreadPoolfromopencensus.common.runtime_contextimportRuntimeContextdefwork(name):# here you will get the context from the parent threadprint(RuntimeContext)pool=ThreadPool(2)# propagate context explicitlypool.map(RuntimeContext.with_current_context(work),['bear','cat','dog','horse','rabbit',])pool.close()pool.join()