第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

Python中Java的InheritableThreadLocal對(duì)等實(shí)現(xiàn)

標(biāo)簽:
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()来创建一个线程,同样没有副作用

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

點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺(jué)得本文不錯(cuò),就分享一下吧!

評(píng)論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評(píng)論
  • 收藏
  • 共同學(xué)習(xí),寫(xiě)下你的評(píng)論
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶(hù)
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得

100積分直接送

付費(fèi)專(zhuān)欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)

舉報(bào)

0/150
提交
取消