TransmittableThreadLocal和InheritableThreadLocal区别
时间: 2023-12-12 18:34:52 浏览: 92
TransmittableThreadLocal和InheritableThreadLocal都是用于解决线程间上下文传递的问题,但是它们的实现方式略有不同。
TransmittableThreadLocal是可传输的线程局部变量,它可以在使用线程池等会池化复用线程的执行组件情况下,提供ThreadLocal值的传递功能。也就是说,当一个线程从线程池中取出来执行任务时,它可以获取到之前设置的TransmittableThreadLocal的值,从而保证了上下文的传递。TransmittableThreadLocal继承自InheritableThreadLocal。
而InheritableThreadLocal是可继承的线程局部变量,它用于父线程传递本地变量到子线程。当一个线程创建子线程时,子线程可以获取到父线程设置的InheritableThreadLocal的值,从而保证了上下文的传递。InheritableThreadLocal继承自ThreadLocal,并且重写了父类的方法:childValue、getMap、createMap。
因此,TransmittableThreadLocal和InheritableThreadLocal的区别在于它们的应用场景和实现方式不同。
代码演示如下:
```python
import threading
from threading import Thread, current_thread
from concurrent.futures import ThreadPoolExecutor
from threading import Lock
from concurrent.futures import Future
from threading import Event
from threading import Semaphore
from threading import Barrier
from threading import Condition
from threading import Timer
from threading import ThreadLocal, local
from concurrent.futures import as_completed
from concurrent.futures import wait
from concurrent.futures import FIRST_COMPLETED
from concurrent.futures import ALL_COMPLETED
from collections import deque
from threading import InheritableThreadLocal, current_thread
from threading import Thread
# InheritableThreadLocal
class MyLocal(InheritableThreadLocal):
def __init__(self, value):
self.value = value
def __repr__(self):
return str(self.value)
local_data = MyLocal(1)
def worker():
print(current_thread().getName(), 'starts with', local_data)
local_data.value += 1
print(current_thread().getName(), 'ends with', local_data)
t = Thread(target=worker)
t.start()
t.join()
# TransmittableThreadLocal
from pytransmit import TransmitThreadLocal
transmit_data = TransmitThreadLocal()
def worker():
print(current_thread().getName(), 'starts with', transmit_data.get())
transmit_data.set(2)
print(current_thread().getName(), 'ends with', transmit_data.get())
t = Thread(target=worker)
t.start()
t.join()
```
阅读全文