亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Python中Java的InheritableThreadLocal對等實現

標簽:
Python

背景

后端接收到一个用户请求后,在请求其他第三方接口时,需要携带用户请求中的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()来创建一个线程,同样没有副作用

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

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消