Python中线程局部值的生命周期是什么时候?

Car*_*nte 8 python multithreading

import threading

mydata = threading.local()

def run():
    # When will the garbage collector be able to destroy the object created
    # here? After the thread exits from ``run()``? After ``join()`` is called?
    # Or will it survive the thread in which it was created, and live until
    # ``mydata`` is garbage-collected?
    mydata.foo = object()

t = threading.Thread(target=run)
t.start()
t.join()
Run Code Online (Sandbox Code Playgroud)

har*_*dsv 7

这是我的答案,因为我没有在前面的答案中看到结论.

我开始想知道同样的事情并尝试了一个与其他答案类似的测试程序,我的结论是他们确实比程序结束时更早得到GCed,这意味着,这些引用可以被确定为垃圾一旦线程本身就死了.

import time
import threading
import gc

data = threading.local()

class Resource(object):
    def __init__(self):
        self.name = threading.currentThread().name
        print 'create: %s' % self.name

    def __del__(self):
        print 'delete: %s' % self.name

def access_thlocal():
    data.key = Resource()

for i in range(0, 10):
    threading.Thread(target=access_thlocal).start()
time.sleep(1)
print "Triggering GC"
gc.collect()
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

输出:

create: Thread-1
create: Thread-2
delete: Thread-1
create: Thread-3
delete: Thread-2
create: Thread-4
delete: Thread-3
create: Thread-5
delete: Thread-4
create: Thread-6
delete: Thread-5
create: Thread-7
delete: Thread-6
create: Thread-8
delete: Thread-7
create: Thread-9
delete: Thread-8
create: Thread-10
delete: Thread-9
Triggering GC
delete: Thread-10
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,删除似乎一旦线程死亡就会发生.


Ale*_*lli 3

Mark 说得几乎是对的——本质上“mydata”将保存对其中所有 TL 变量的引用,无论它们是从哪个线程创建的。以机智...:

import threading
import gc

mydata = threading.local()

class x:
    def __del__(self):
        print "x got deleted!"

def run():
    mydata.foo = x()

t = threading.Thread(target=run)
print "t created"
gc.collect()
t.start()
print "t started"
gc.collect()
del mydata
print "mydata deleted"
gc.collect()
t.join()
print "t joined"
gc.collect()
print "Done!"
Run Code Online (Sandbox Code Playgroud)

发出:

t created
t started
x got deleted!
mydata deleted
t joined
Done!
Run Code Online (Sandbox Code Playgroud)

gc 实际上在 CPython 中不起任何作用,因此您可以将代码简化为:

import threading

mydata = threading.local()

class x:
    def __init__(self):
        print "x got created!"
    def __del__(self):
        print "x got deleted!"

def run():
    mydata.foo = x()

t = threading.Thread(target=run)
print "t created"
t.start()
print "t started"
del mydata
print "mydata deleted"
t.join()
print "t joined"
print "Done!"
Run Code Online (Sandbox Code Playgroud)

仍然看到...:

t created
x got created!
t started
x got deleted!
mydata deleted
t joined
Done!
Run Code Online (Sandbox Code Playgroud)