考虑以下代码:
#/usr/bin/env python
from time import sleep
from random import random
from threading import Thread, local
data = local()
def bar():
print("I'm called from", data.v)
def foo():
bar()
class T(Thread):
def run(self):
sleep(random())
data.v = self.getName() # Thread-1 and Thread-2 accordingly
sleep(1)
foo()
>> T().start(); T().start()
我是从 Thread-2 调用的
我是从 Thread-1 调用的
这里 threading.local() 被用作将一些数据从 run() 传递到 bar() 而不更改 foo() 接口的快速而肮脏的方法。
请注意,使用全局变量并不能解决问题:
#/usr/bin/env python
from time import sleep
from random import random
from threading import Thread
def bar():
global v
print("I'm called from", v)
def foo():
bar()
class T(Thread):
def run(self):
global v
sleep(random())
v = self.getName() # Thread-1 and Thread-2 accordingly
sleep(1)
foo()
>> T().start(); T().start()
我是从 Thread-2 调用的
我是从 Thread-2 调用的
同时,如果您能负担得起将这些数据作为 foo() 的参数传递 - 这将是一种更优雅且设计良好的方式:
from threading import Thread
def bar(v):
print("I'm called from", v)
def foo(v):
bar(v)
class T(Thread):
def run(self):
foo(self.getName())
但这在使用第三方或设计不佳的代码时并不总是可行的。