Python中Java的InheritableThreadLocal对等实现

背景

后端接收到一个用户请求后,在请求其他第三方接口时,需要携带用户请求中的trace_id,以便后续梳理请求链路和定位问题。

原有的代码基于Python的Django框架开发,不同的用户请求之间是线程隔离的,不同用户请求的trace_id自然也不同。除此之外,为了便于读取trace_id所以将其存储为一个全局变量。基于这两点,原代码中采用threading.local()来存储trace_id。

为了加快请求速度,需要通过多线程来并发请求第三方接口(PS:也可以使用协程,但是原有的接口调用封装并不支持异步,改动起来工作量太大)。但是由于threading.local()本就是线程隔离的,所以子线程根本无法拿到父线程(请求线程)的trace_id,然后就会出现报错:'_thread._local' object has no attribute 'trace_id'

在简单的搜索以后,发现Java中自带InheritableThreadLocal(与ThreadLocal不同,使用InheritableThreadLocal创建的变量的属性可以被子线程继承,以继续使用)。但是不清楚为什么Python没有(PS:事实上stackoverflow上面也有提问,但是不知道为什么没有回答),所以做了一个简单的实现。

代码实现

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import copy
from _threading_local import local
from weakref import ref

from threading import current_thread, Thread

inheritable_local_list = []


def copy_dict(local_obj, child_thread):
    """copy parent(current) thread local_obj dict for the child thread, and return it."""

    impl = local_obj._local__impl
    localdict = copy.deepcopy(impl.dicts[id(current_thread())][1])
    key = impl.key
    idt = id(child_thread)

    def local_deleted(_, key=key):
        # When the localimpl is deleted, remove the thread attribute.
        thread = wrthread()
        if thread is not None:
            del thread.__dict__[key]

    def thread_deleted(_, idt=idt):
        # When the thread is deleted, remove the local dict.
        # Note that this is suboptimal if the thread object gets
        # caught in a reference loop. We would like to be called
        # as soon as the OS-level thread ends instead.
        local = wrlocal()
        if local is not None:
            dct = local.dicts.pop(idt)

    wrlocal = ref(impl, local_deleted)
    wrthread = ref(child_thread, thread_deleted)
    child_thread.__dict__[key] = wrlocal
    impl.dicts[idt] = wrthread, localdict
    return localdict


class InheritableThread(Thread):
    def __init__(self, *args, **kwargs):
        Thread.__init__(self, *args, **kwargs)
        global inheritable_local_list
        for local_obj in inheritable_local_list:
            copy_dict(local_obj, self)


class InheritableLocal(local):
    """
    Please use InheritableThread to create threads, if you want your son threads can inherit parent threads' local
    """

    def __init__(self):
        global inheritable_local_list
        inheritable_local_list.append(self)

threading.local()的结构:

file

使用方法

thread_ctx = InheritableLocal()
t = InheritableThread(target=function, args=(arg1, arg2, arg3))
t.start()
t.join()
  1. 使用InheritableLocal()替代threading.local()来创建一个线程环境变量,没有其他副作用
  2. 使用InheritableThread()替代Thread()来创建一个线程,同样没有副作用

然后创建出来的子线程就可以继承父线程的环境变量了,当然两个线程之间的环境变量还是相互隔离的,继承只会发生在子线程创建时。

你可能感兴趣的:(Python中Java的InheritableThreadLocal对等实现)