访问不同模块中的线程本地对象-Python [英] Access thread local object in different module - Python

查看:120
本文介绍了访问不同模块中的线程本地对象-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,请忍受我的问题.

I'm new to Python so please bear with my question.

假设我的应用程序有一个名为message_printer的模块,该模块仅定义了一个print_message函数来打印消息.现在在我的主文件中,我创建了两个线程,它们在message_printer中调用了print函数.

Let's say my application has a module named message_printer which simply defines a print_message function to print the message. Now in my main file, I create two threads which calls print function in message_printer.

我的问题是:如何为每个线程设置不同的消息并在message_printer中访问它?

My question is: How can I set a different message per thread and access it in message_printer?

message_printer:

message_printer:

import threading

threadLocal = threading.local()

def print_message():
   name = getattr(threadLocal, 'name', None);
   print name
   return

主要:

import threading
import message_printer

threadLocal = threading.local()

class Executor (threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        threadLocal.name = name

    def run(self):
        message_printer.print_message();

A = Executor("A");
A.start();
B = Executor("B");
B.start();

这只是输出NoneNone,而我希望AB.我还尝试了直接在print_message函数内部访问threadLocal对象,但是不起作用.

This just outputs None and None while I expect A and B. I also tried accessing threadLocal object inside the print_message function directly but doesn't work.

请注意,这仅是示例.在我的应用程序中,确切的用例是用于日志记录. Main启动一堆线程,这些线程调用其他模块.我希望每个线程都有一个不同的记录器(每个线程都应记录到其自己的文件中),并且每个记录器都需要在Main中进行配置.因此,我试图实例化每个线程的记录器,并在线程本地存储中进行设置,然后可以在其他模块中进行访问.

Note that this is just an example. In my application, the exact use case is for logging. Main launches a bunch of thread which call other modules. I want to have a different logger per thread (each thread should log to its own file) and each logger needs to be configured in Main. So I'm trying to instantiate logger per thread and set in thread local storage which can then be accessed in other modules.

我做错了什么?我以这个问题为例 Python中的线程本地存储

What am I doing wrong? I'm following this question as an example Thread local storage in Python

推荐答案

代码的问题是,您没有将name分配给正确的local()上下文.在通过调用.start()启动AB线程之前,__init__()方法在主线程中运行.

The problem with your code, is that you are not assigning your name to the correct local() context. Your __init__() method is run in the main thread, before you start your A and B threads by calling .start().

您的第一个线程创建A = Executor("A");将创建一个新线程A,但会更新主线程的本地上下文.然后,当通过调用A.start();来启动A时,将输入A:s上下文,并带有单独的本地上下文.此处未定义name,最终以None作为输出.然后,B也会发生同样的情况.

Your first thread creation A = Executor("A"); will create a new thread A but update the local context of the main thread. Then, when you start A by calling A.start(); you will enter A:s context, with a separate local context. Here name is not defined and you end up with None as output. The same then happens for B.

换句话说,要访问线程局部变量,您应该运行当前线程,即运行.start()时(将调用.run()方法),而不是创建对象时(运行).

In other words, to access the thread local variables you should be running the current thread, which you are when running .start() (which will call your .run() method), but not when creating the objects (running __init__()).

要使当前代码正常工作,您可以将数据存储在每个对象中(使用self引用),然后在每个线程运行时,将内容复制到线程本地上下文中:

To get your current code working, you could store the data in each object (using self references) and then, when each thread is running, copy the content to the thread local context:

import threading

threadLocal = threading.local()

def print_message():
   name = getattr(threadLocal, 'name', None);
   print name
   return

class Executor (threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        # Store name in object using self reference
        self.name = name

    def run(self):
        # Here we copy from object to local context,
        # since the thread is running
        threadLocal.name = self.name
        print_message();

A = Executor("A")
A.start()
B = Executor("B")
B.start()

但是请注意,在这种情况下,使用线程局部上下文有点过大,因为我们已经将单独的数据值存储在不同的对象中.要直接从对象中使用它,则需要对print_message()进行少量重写.

Note, though, in this situation, it is somewhat of an overkill to use the thread local context, since we already store the separate data values in the different objects. To use it directly from the objects, would require a small rewrite of print_message() though.

这篇关于访问不同模块中的线程本地对象-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆